evanrelf evanrelf - 1 month ago 10
Javascript Question

Trouble listing files with fs.readdir() in Node.js

I'm working my way through the "Learn You The Node.js For Much Win!" workshop but I'm having trouble on exercise 5. It asks you to

Create a program that prints a list of files in a given directory, filtered by the extension of the files.


I passed in the directory,
files
, that contains an assortment of JavaScript, Ruby, and plain text files. It is supposed to
console.log()
each file with the
.js
extension.

var fs = require('fs');

function indexDirectory(directory) {
fs.readdir(directory, function(err, files) {
for (var i in files) {
if (i.indexOf('.js') != -1) {
console.log(files[i]);
}
}
});
}

indexDirectory('files');


My current code does not output anything when I run it with
node program.js
. Am I missing some asynchronous principle? Am I using callbacks incorrectly? Any help would be appreciated :)

Answer

files are array, you should use forEach instead of for .. in

var fs = require('fs');

function indexDirectory(directory) {
  fs.readdir(directory, function(err, files) {
    files.forEach(function (file) {
      if (file.indexOf('.js') != -1) {
        console.log(file);
      }
    });  
  });
}

indexDirectory('files');
Comments