1

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

2
  • 1
    A for in loop iterates over keys, not values; don’t use it on arrays. files.forEach(function (i) { … }). See also stackoverflow.com/questions/500504/…. Commented Nov 30, 2014 at 19:37
  • for (var i = 0, file; i < files.length; i++) { file = files[i]} || files.forEach(function (file) {}); || files.filter(function(file){ return FILE_IS_JS; }); Commented Nov 30, 2014 at 19:39

2 Answers 2

3

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');
Sign up to request clarification or add additional context in comments.

Comments

0

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]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.