【发布时间】:2017-03-22 22:02:39
【问题描述】:
当我尝试在 node.js 的 async.waterfall 中使用 list.forEach 方法时,我收到了错误消息: if (fn === null) throw new Error("Callback is already called.");
错误:回调已被调用。
我想要的是对目录中的每个文件进行一些更改。
/**
* Created by slow_time on 2017/3/22.
*/
var fs = require('fs');
var async = require('async');
var _dir = './data/';
//writeStream is used to log something
var writeStream = fs.createWriteStream('log.txt',
{
'flags': 'a',
'encoding': 'utf8',
'mode': 0666
});
try {
//use the method waterfall
async.waterfall([
//read the directory
function (callback) {
fs.readdir(_dir, function (err, files) {
callback(err, files);
});
},
function (files, callback) {
//Here is what I guess, something wrong with it
files.forEach(function (name) {
callback(null, name);
});
},
//The code below is right, I think.
function (file, callback) {
fs.stat(_dir + file, function (err, stats) {
if(stats.isFile())
callback(err, stats, file);
});
},
//judge whether it is a file or a directory
function (stats, file, callback) {
fs.readFile(_dir + file, 'utf8', function (err, data) {
callback(err, file, data);
});
},
// do some changes to the file content
function (file, data, callback) {
var adjData = data.replace(/somecompany\.com/g, 'burningbird.net');
fs.writeFile(_dir + file, adjData, function (err) {
callback(err, file);
});
},
//write the changes back to the file
function (file, callback) {
writeStream.write('changed ' + file + '\n', 'utf8', function (err) {
callback(err, file);
});
}
], function (err, result) {
if(err) throw err;
console.log('modified ' + result);
});
} catch(err) {
console.log(err);
}
【问题讨论】:
-
您在哪一行出现错误?
-
您不能使用
async.waterfall为这样的列表中的每个元素运行代码。您需要使用async.map。 -
谢谢,首先。你的意思是我永远不能在 async.waterfall 中使用 forEach 方法?但它是书中的演示。以及如何在我的情况下使用 async.map?
标签: javascript node.js asynchronous