So Im trying to use the nodejs express FS module to iterate a directory in my app, store each filename in an array, which I can pass to my express view and iterate through the l
fs.readdir
is asynchronous (as with many operations in node.js). This means that the console.log
line is going to run before readdir
has a chance to call the function passed to it.
You need to either:
Put the console.log
line within the callback function given to readdir
, i.e:
fs.readdir('./myfiles/', function (err, files) { if (err) throw err;
files.forEach( function (file) {
myfiles.push(file);
});
console.log(myfiles);
});
Or simply perform some action with each file inside the forEach
.