i具有以下nodejs代码。我的目的是在所有文件中产生所有行的一项计数。但是,当我运行此代码时,我只收到最小文件的数量。
我想我明白了为什么。所有6个读取的文件都可以快速连续启动,自然而然的是,最短的文件首先完成,并且不会等待所有其他阶段完成。
我的问题是:解决此问题的最佳方法是什么?在现实生活中,我想进行比每次增加计数器更复杂的操作,但这会跨越整个想法。
我应该以某种方式使用诺言,或者可能会从其他类型的事件中关注?
var fs = require("fs");
var readline = require('readline');
var TOTAL_LINES = 0;
allCSVFiles = ["a", "b", "c", "d", "e", "f"];
allCSVFiles.forEach(function(file, idx, array){
var pathToFile = `/scratch/testDir/${file}.csv`;
var rd = readline.createInterface({
input: fs.createReadStream(pathToFile),
// output: process.stdout,
console: false
});
rd.on('line', function(line) {
TOTAL_LINES++;
})
.on('close', function() {
console.log (`closing: ${pathToFile}`);
if (idx === array.length - 1){
console.log (`Grand total: ${TOTAL_LINES}`);
}
})
});
是的,您可以使用Promise进行异步读取文件。由于Node.js的异步性质,只需使用fs.ReadFile即可导致所有对所有文件进行处理的文件。
参考:http://www.yaoyuyang.com/2017/01/20/nodejs-batch-file-processing.html
此示例显示创建一个texalsummary的空文件,然后如何将每个承诺完成的文件附加到文件上。在您的情况下,请在附加目标摘要文件之前使用Promise,请阅读现有文件内容以捕获上一行计数,然后根据汇总总数进行总和并更新文件。
建议:如果您的运行时间很长,则应启动另一个过程(使用Child_process创建(进行并行处理,然后将您的node.js过程异步等待结果。
参考:node.js
中的并行任务在Node.js
中执行并行处理的最佳方法所以请解释您的用例。
好吧,我认为我对自己的问题有答案。请随时批评它。
var fs = require("fs");
var readline = require('readline');
var TOTAL_LINES = 0;
var allMyPromises = [];
allCSVFiles = ["a", "b", "c", "d", "e", "f"];
allCSVFiles.forEach(function(file, idx, array){
var myPromise = readOneFile (file, idx, array);
allMyPromises.push (myPromise);
});
Promise.all(allMyPromises).then(function(values) {
console.log (`Grand total: ${TOTAL_LINES}`);
});
function readOneFile(file,idx, array){
return new Promise(function(resolve, reject) {
var pathToFile = `/scratch/testDir/${file}.csv`;
var rd = readline.createInterface({
input: fs.createReadStream(pathToFile),
// output: process.stdout,
console: false
});
rd.on('line', function(line) {
TOTAL_LINES++;
})
.on('close', function() {
console.log (`closing: ${pathToFile}`);
resolve (TOTAL_LINES);
})
}
)
}