简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM