node.jsfs

reading files asynchronously in parallel


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?


Solution

  • Pretty easy.

    var files = [...], remaining = files.length;
    var callback = function () {
        remaining--;
        if (!remaining) {
            go();
        }
    };
    files.forEach(function(file) {
        fs.readFile(file, callback);
    });