NodeJS中的多个writeFile

kir*_*uga 5 javascript node.js

我有一项任务是将部分数据写入单独的文件:

        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.');
            }
        });
Run Code Online (Sandbox Code Playgroud)

但现在我有4个不同的回调,所以当完成所有4个任务时,我无法得到这个时刻.是否可以并行4个writeFile调用并且只获得1个回调,这将在创建4个文件时调用?

PS

当然,我可以这样做:

fs.writeFile('a.json', data, function(err) {
  fs.writeFile('b.json', data, function(err) {
    ....
    callback();
  }
}
Run Code Online (Sandbox Code Playgroud)

只是好奇有没有其他方法来做到这一点.谢谢.

Ger*_*osi 10

您可以使用该async模块.它还有助于清理代码:

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');
    }
});
Run Code Online (Sandbox Code Playgroud)