当我尝试在node.js中的async.waterfall中使用list.forEach方法时,我收到了错误消息: if(fn === null)抛出新错误(“Callback已被调用。”);
错误:已经调用了回调。
我想要的是对目录中的每个文件进行一些更改。
/**
* 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);
}
答案 0 :(得分:1)
因为你在foreach中调用回调它给出错误。 你的代码 -
files.forEach(function (name) {
callback(null, name);
});
完成操作后,回拨应仅调用一次。 这样做也是如此:
files.forEach(function (name) {
});
callback(null, name);