Question

My node.js application requires several files. I understand that it's recommended to read files asynchronously, so, apparently I have to do something like this:

fs.readFile("file1", function(...) {
  fs.readFile("file2", function(...) {
    fs.readFile("file3", function(...) {
       [my application]
    }
  }
}

However, in this case, the files will be read sequentially.

Is there a way to read many files in parallel, and still make sure that the application starts after ALL of them have been loaded?

Was it helpful?

Solution

Pretty easy.

var files = [...], remaining = files.length;
var callback = function () {
    remaining--;
    if (!remaining) {
        go();
    }
};
files.forEach(function(file) {
    fs.readFile(file, callback);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top