A: 是的,node 可以同时读取 4 个文件。
我的回答是,这取决于您的情况,同步或异步读取文件。如果是配置数据,或者文件可以缓存,我建议同步做,很简单,只做一次。因此,您不会等待太多。初始化的长操作是典型的,从长远来看可以使事情更有效。话虽如此,按顺序异步读取四个文件,以便您的程序可以在后台执行其他操作并不难。我将处理每个同步和异步示例并添加编辑。
/* jshint node:true*/
var fs = require('fs');
function readFilesSync(fileNames) {
'use strict';
var results = '';
for (var i = 0; i < fileNames.length; i++) {
results += fs.readFileSync(fileNames[i]);
}
return results;
}
function readFiles(fileNames, callback) {
'use strict';
var results = '';
function readFile(index) {
if (index < fileNames.length) {
fs.readFile(fileNames[index], function (err, data) {
results += data;
readFile(index + 1);
});
} else {
callback(results);
}
}
readFile(0);
}
function readAllFilesAtOnce(fileNames, callback) {
'use strict';
var results = {};
var numFiles = fileNames.length;
function callBackWrapper() {
var resultsOrdered = '';
for (var i = 0; i < fileNames.length; i++) {
resultsOrdered += results[fileNames[i]];
}
callback(resultsOrdered);
}
function readFileAsync(fileName) {
fs.readFile(fileName, function (err, data) {
results[fileName] = data;
numFiles--;
if (numFiles === 0) {
callBackWrapper();
}
});
}
for (var i = 0; i < fileNames.length; i++) {
readFileAsync(fileNames[i]);
}
}
function doSomethingWithTheData(data) {
'use strict';
console.log('Results async: ' + data);
}
function doSomethingWithTheData2(data) {
'use strict';
console.log('Results async all at once: ' + data);
}
var fileNamesArray = ['blah.js', 'file.js', 'hello.txt'];
console.log('The results sync: ' + readFilesSync(fileNamesArray));
readFiles(fileNamesArray, doSomethingWithTheData);
readAllFilesAtOnce(fileNamesArray, doSomethingWithTheData2);
编辑:在那里我添加了一种方法来一次读取所有文件。
Process.nextTick 只是在事件循环的下一次处理这个函数。前任:
process.nextTick(function() {
console.log('never printed out');
});
while(true);
例 2:
process.nextTick(function() {
console.log('printed last');
});
console.log('printed first');