0

I'm trying to learn node.js by using "learnyounode". There is an excercise where one is supposed to take a folder-path and a file-extension type as input and then give all files of that type in that folder as output. I have constructed this program:

var fs = require('fs');
var pathModule = require('path');
var path = process.argv[2];
var ext = '.'.concat(process.argv[3]);
filteredList = [];
fs.readdir(path,function doneReading(err, list){
    for(var i = 0; i < list.length; i++){
        if(pathModule.extname(list[i]) == ext){
            filteredList.push(list[i]);
        }
    }
    })

for(var i = 0; i < filteredList.length; i++){
    console.log(filteredList[i]);
}

and for some reason the

filteredList.push(list[i]);

has no effect on the contents of the filteredList. Why is this? I have solved the excercise by moving the console.log to inside the readdir-function, but I have no idea why the psuh doesn't work.

Sikorski
  • 2,653
  • 3
  • 25
  • 46
Lonneberga
  • 13
  • 7
  • 1
    fs.readdir is asynchronous - you're outputting the filteredList before fs.readdir has called your callback function - output the list inside that callback and it will output correctly – Jaromanda X Sep 28 '16 at 13:31

1 Answers1

1

The function doneReading does affect the filteredList, its just that you are not waiting for it. The fs.readdir function is asynchronous that is it takes a callback. Callbacks are invoked when the method invoking them has finished its work. Callback doesn't block the program execution thus printing the list null. Try changing your code to this :

fs.readdir(path,function doneReading(err, list){
    for(var i = 0; i < list.length; i++){
        if(pathModule.extname(list[i]) == ext){
            filteredList.push(list[i]);
        }
    }
    for(var i = 0; i < filteredList.length; i++){
        console.log(filteredList[i]);
    }
})
Sikorski
  • 2,653
  • 3
  • 25
  • 46