当我尝试在 Node.js 的 async.waterfall 中使用 list.forEach 方法时,出现错误消息: if (fn === null) throw new Error("回调已被调用。");
错误:回调已被调用。
我想要的是对目录中的每个文件进行一些更改。
/**
* 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);
}
最佳答案
当您在 foreach 中调用回调时,会出现错误。 您的代码 -
files.forEach(function (name) {
callback(null, name);
});
回调应该只在您完成操作后调用一次。 因此,请进行以下更改:
files.forEach(function (name) {
});
callback(null, name);
关于javascript - 回调已经被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42953562/