gpt4 book ai didi

javascript - js异步读取文件

转载 作者:太空宇宙 更新时间:2023-11-04 03:07:24 25 4
gpt4 key购买 nike

我有一个文件列表。我有兴趣读出它们的名字和它们包含的行数。我知道有更简单的方法可以做到这一点,但是有没有办法使用下面代码的一般结构来完成此任务?

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com