-1

Why if you do:

for (var i = 0; i < 5; i++) {
    fs.readFile('file' + i, function(err, data) {
      console.log('file: ', data);
    });
}

you get different results each time?

I'm guessing it has something to do with node's "async" Event Loop but not really sure how this works.

LasagnaAndroid
  • 2,815
  • 1
  • 16
  • 20
  • fs.readFile is async. You answered your own question. Files may be read at different speeds. – Jordan Soltman Dec 06 '16 at 21:36
  • I know its async, I want to know what makes the difference each time, is it random?, why doesn't it return them in the same order each time? It's not making an external request, it's just reading files, so why does it read them in different order each time, what makes it be faster at reading one or the other?. You can read the answer I chose to understand what I was asking ;) – LasagnaAndroid Dec 14 '16 at 02:25

3 Answers3

1

The asynchronous fs methods utilize libuv's thread pool and the execution of those threads can be ordered/scheduled differently by the operating system (especially depending on the type of scheduler used by the operating system).

mscdex
  • 104,356
  • 15
  • 192
  • 153
0

This will go off and fetch a files, returning the data to your callback when each completes. You'll never know which ones will complete first or the order. If you need to wait for all 5 files before you do something look into the async library: https://www.npmjs.com/package/async.

fs.readFile('file' + i, function(err, data) {
  console.log('file: ', data);
});
Jordan Soltman
  • 3,795
  • 17
  • 31
0

You can do this :-

for (var i = 0; i < 5; i++) {
    // put the statement in try-catch in case some of the files do not exists or
    // you get some other error
    try {
        // to show actual contents of the file instead of a buffer
        console.log(fs.readFileSync('file' + i).toString());
    } catch (error) {
        console.error(error);
    }
}

I would suggest against using this but if you have to then this is one of the way. You should checkout async.js http://caolan.github.io/async/docs.html#map as suggested by @jordan-s.

PratikGandhi
  • 173
  • 1
  • 10
  • Yeah, not actually looking for a different way to this, I just want to know why the order on async processes returns unordered if they are always called in the same order. – LasagnaAndroid Dec 08 '16 at 21:05