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 :)
for inloop iterates over keys, not values; don’t use it on arrays.files.forEach(function (i) { … }). See also stackoverflow.com/questions/500504/….for (var i = 0, file; i < files.length; i++) { file = files[i]}||files.forEach(function (file) {});||files.filter(function(file){ return FILE_IS_JS; });