Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple writeFile in NodeJS

I have a task to write parts of the data to separate files:

        fs.writeFile('content/a.json', JSON.stringify(content.a, null, 4), function(err) {
            if(err) {
                console.log(err);
            } else {
                console.log('a.json was updated.');
            }
        });
        fs.writeFile('content/b.json', JSON.stringify(content.b, null, 4), function(err) {
            if(err) {
                console.log(err);
            } else {
                console.log('b.json was updated.');
            }
        });
        fs.writeFile('content/c.json', JSON.stringify(content.c, null, 4), function(err) {
            if(err) {
                console.log(err);
            } else {
                console.log('c.json was updated.');
            }
        });
        fs.writeFile('content/d.json', JSON.stringify(content.d, null, 4), function(err) {
            if(err) {
                console.log(err);
            } else {
                console.log('d.json was updated.');
            }
        });

But now I have 4 different callbacks, so I can't get the moment, when all 4 task have been finished. Is it possible to parallel 4 writeFile calls and get only 1 callback, which will be called when 4 files was created?

P.S.

Of course I can do smth like:

fs.writeFile('a.json', data, function(err) {
  fs.writeFile('b.json', data, function(err) {
    ....
    callback();
  }
}

Just curious is there any other way to do this. Thanks.

like image 212
kirill.buga Avatar asked Oct 16 '14 20:10

kirill.buga


1 Answers

You can use the async module. It also helps cleaning up your code:

var async = require('async');

async.each(['a', 'b', 'c', 'd'], function (file, callback) {

    fs.writeFile('content/' + file + '.json', JSON.stringify(content[file], null, 4), function (err) {
        if (err) {
            console.log(err);
        }
        else {
            console.log(file + '.json was updated.');
        }

        callback();
    });

}, function (err) {

    if (err) {
        // One of the iterations produced an error.
        // All processing will now stop.
        console.log('A file failed to process');
    }
    else {
        console.log('All files have been processed successfully');
    }
});
like image 156
Gergo Erdosi Avatar answered Sep 18 '22 13:09

Gergo Erdosi