Search code examples
node.jsasynchronousread-write

NodeJS - How to read multiple files asynchronously and write read contents to one file


I would like to read multiple files asynchronously in NodeJS. It is good to read multiple files at the same time, when the order of reading doesn't matter.

However, I'm trying to write contents of these files together into one file. I can write a file just fine, but how do I make sure that all the files have been read before I write all the contents into that one file?


Solution

  • User Promises by one of the following method

    1. Create promises, each one is resolved when file is read
    2. Use bluebird to create Promise-like methods for fs
    3. Use fs-promise module

    Then save all this promises into array and use Promise.all

    Other way around can be iterating variable i.e. var filesRead = 0. When file is read, increase this number filesRead++. After this, always check, if you read all the files, if so, you can do the writing

    if (filesRead === numberOfFilesToRead){
        //write things
    }