我有一个文件列表。我有兴趣读出它们的名字和它们包含的行数。我知道有更简单的方法可以做到这一点,但是有没有办法使用下面代码的一般结构来完成此任务?
var fs = require('fs');
var fileList = ['./newtest.js', './globtime.js', './newtest.js'];
var numLines = 0;
var filesCount = 0;
function returnLines () {
console.log('the length of all files is ' + numLines);
}
function readLines(files) {
for (file in files) {
fs.readFile(files[file], function(err, data) {
if (data != undefined) {
var array = data.toString().split("\n");
numLines += array.length;
filesCount +=1;
console.log('the length of ' + files[file] + ' is ' + array.length); // get this to work ..
if (filesCount == files.length) {
returnLines();
}
}
});
}
}
readLines(fileList);
最佳答案
你可以用闭包来做到这一点:
var fs = require('fs');
var fileList = ['./newtest.js', './globtime.js', './newtest.js'];
var numLines = 0;
var filesCount = 0;
function returnLines () {
console.log('the length of all files is ' + numLines);
}
function readLines(files) {
var readFile = function(name){
return fs.readFile(name, function(err, data) {
if (data != undefined) {
var array = data.toString().split("\n");
numLines += array.length;
filesCount +=1;
console.log('the length of ' + name + ' is ' + array.length); // get this to work ..
if (filesCount == files.length) {
returnLines();
}
}
});
};
for (file in files) {
readFile(files[file]);
}
}
readLines(fileList);
关于javascript - js异步读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35930674/