NodeJS中的多个writeFile

时间:2014-10-16 20:28:05

标签: 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.');
            }
        });

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

P.S。

当然,我可以这样做:

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

很奇怪还有其他方法可以做到这一点。感谢。

5 个答案:

答案 0 :(得分: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');
    }
});

答案 1 :(得分:3)

是的,您应该使用async,并行方法如下所示:

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
});

答案 2 :(得分:2)

更简洁的方法就是通过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);
}

答案 3 :(得分:1)

我认为我会使用promises提供一种不同的方法,这种方法非常适合知道多个异步操作何时完成。此特定解决方案使用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 
});

答案 4 :(得分:0)

使用es6,您可以:



function writeFile(file, index) {
    return new Promise((resolve, reject) => {
        let  fileUrl = `content/${index}.json`;
        fs.writeFile(fileUrl, JSON.stringify(file, null, 4),
          (err) => {
              if (err)
                  reject (err);
              else
                  resolve(fileUrl)
          });
    });
}
let files = Object.keys(content).map(key => writeFile(content[key]));
Promise.all(files).then(values => {/*Files Urls*/}, err => {/*Some Error*/});




相关问题