evanrelf
evanrelf

Reputation: 303

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 :)

Upvotes: 1

Views: 4183

Answers (2)

Oleksandr T.
Oleksandr T.

Reputation: 77482

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');

Upvotes: 3

dmitreyg
dmitreyg

Reputation: 2625

One more problem with this code is that it will print also files with '.json' extension. So instead of indexOf you should use, for example, regular expressions. Something like this:

var matches = new RegExp(".js$").test(files[i]);
if (matches) {
   console.log(files[i]);
}

Upvotes: 0

Related Questions