wyc
wyc

Reputation: 55273

Why is the following readFileSync function returning undefined?

I want to read files from a folder and then return the result plus some xhtml:

#! /usr/bin/env node

var fs = require('fs'),
    files = fs.readdirSync(__dirname + '/files/')

var manifest = function() {
  files.forEach((file) => {
    return `<item href="${file}.html" id="html30" media-type="application/xhtml+xml"/>`
  })
}

console.log(manifest())

console.log(manifest()) returnes undefined, though. Not sure why, since console.log(contents) returns the result:

foo 1

foo 2

foo 3

Upvotes: 0

Views: 844

Answers (1)

Nick Tomlin
Nick Tomlin

Reputation: 29221

Returning a string from forEach isn't going to assign anything since ForEach does not produce any side effects. From mdn

forEach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.

You'll need to reduce over your files (into a string) or mutate a variable.

var manifest = function() {
  return files.reduce((items, file) => {
    let contents = fs.readFileSync(__dirname + '/files/' + file, 'utf8')
    return items + `<item href="${file}.html" id="html30" media-type="application/xhtml+xml"/>`
  }, '');
}

Upvotes: 1

Related Questions