node是可以异步读取文件,但是如果一下子异步读取的数量过大,则会抛出20错误
以下列出3种读取方式:同步,异步转同步,数量约束的异步
var t1, t2;
t1 = +new Date;
fileList.forEach(function(n, i) {
var data = fs.readFileSync(n, {
encoding: "utf-8"
});
if (data && data.indexOf && data.indexOf("templateUrl: 'templates/widget-label.html'") >= 0) {
console.log(n);
}
});
t2 = +new Date;
console.log(t2 - t1);
t1 = +new Date;
async.eachSeries(fileList, function(n, callback) {
fs.readFile(n, "utf-8", function() {
// to do
callback(null, null);
})
}, function(err) {
t2 = +new Date;
console.log(t2 - t1);
console.log("eachSeries end");
})
/*
t1 = +new Date;
fileList.forEach(function(n, i) {
fs.readFile(n, "utf-8", function(err, data) {
// to do
});
});
t2 = +new Date;
console.log(t2 - t1);
*/
t1 = +new Date;
async.eachLimit(fileList, 500, function(n, callback) {
fs.readFile(n, "utf-8", function() {
// to do
callback(null, null);
})
}, function(err) {
t2 = +new Date;
console.log(t2 - t1);
console.log("eachLimit end");
});
时间分别为2564,4007,1207
(我的文件夹下有3000个文件)