nodejs: write multiple files in for loop

Viewed 9157

I am still learning nodejs. This question is related to a few others (e.g., Writing multiple files a loop in Nodejs) but a bit different. It is actually quite simple. I want to write a number of files and when it is all done continue on other task.

Without for loop, I am doing like this,

fs.readFile(f1.path, function(err, data) {
    fs.writeFile("/tmp/" + f1.path, data, function(err) {
        fs.readFile(f2.path, function(err, data) {
            fs.writeFile("/tmp/" + f2.path, data, function(err) {
                ...
                if (err) throw err;

                // do something when all files are written

If I want to convert it using for loop, how to do it? Suppose I could put f1, f2 ... into an array and iterate them.

Thank you for the help.

4 Answers

STEP 1 : Install fs-extra

npm i -D fs-extra

Documentation : https://www.npmjs.com/package/fs-extra

STEP 2 : Write files with fs.outputFile

const fs = require('fs-extra');
// Async
fs.outputFile(file, data, [options, callback])
// Sync
fs.outputFileSync(file, data, [options])

If output directories are not there, they will be created recursively.

Good Luck...

Related