Javascript NodeJS中的多个writeFile

Javascript NodeJS中的多个writeFile,javascript,node.js,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/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.');
            }
        });
但是现在我有4个不同的回调,所以我不能得到所有4个任务都完成的时刻。是否有可能并行4个writeFile调用,只得到1个回调,这将在创建4个文件时调用

附言

当然,我可以做smth,比如:

fs.writeFile('a.json', data, function(err) {
  fs.writeFile('b.json', data, function(err) {
    ....
    callback();
  }
}
只是好奇有没有其他方法可以做到这一点。谢谢。

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

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');
    }
});
是的,您应该使用,并行方法如下所示:

async.parallel([
    function(callback){
        fs.writeFile('content/a.json', JSON.stringify(content.a, null, 4), callback);
    },
    function(callback){
        fs.writeFile('content/b.json', JSON.stringify(content.b, null, 4), callback);
    },
    function(callback){
        fs.writeFile('content/c.json', JSON.stringify(content.c, null, 4), callback);
    },
    function(callback){
        fs.writeFile('content/d.json', JSON.stringify(content.d, null, 4), callback);
    }
],
function(err, results){
    // all done
});

一种更干净的方法。。这将是通过async.map实现的

var async = require('async');

var arr = [{'filename':'content/a.json', 'content':content.a},{'filename':'content/b.json', 'content':content.b}];
async.map(arr, getInfo, function (e, r) {
  console.log(r);
});

function getInfo(obj, callback) {
  fs.writeFile(obj.filename, JSON.stringify(obj.content, null, 4), callback);
}

我想我会提供一种不同的方法,使用承诺,这是了解多个异步操作何时全部完成的理想方法。此特定解决方案使用Bluebird promise库:

var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));

var promises = ["a", "b", "c", "d"].map(function(val) {
    return fs.writeFileAsync('content/' + val + ".json", JSON.stringify(content[val], null, 4));
});

Promise.all(promises).then(function() {
    // all writes are done here
}).catch(function(err) {
    // error here 
});
使用es6,您可以执行以下操作:

函数writeFile(文件、索引){
返回新承诺((解决、拒绝)=>{
让fileUrl=`content/${index}.json`;
writeFile(fileUrl,JSON.stringify(file,null,4),
(错误)=>{
如果(错误)
拒绝(错误);
其他的
解析(文件URL)
});
});
}
让files=Object.keys(content.map)(key=>writeFile(content[key]);

Promise.all(files).then(value=>{/*files url*/},err=>{/*Some Error*/})查找名为
async
的npm模块。您也可以使用内置的
promise
模块,但是异步更容易理解。如果您反对使用其他模块,您也可以使用计数器。每次完成时递增,当complete等于创建的文件总数时,您就知道它们都完成了。谢谢大家,异步模块是我要找的。我对if/else语句之后的callback()有点困惑。它的目的是什么?