在nodejs中异步读取和缓存多个文件

mic*_*nic 4 fs readfile node.js

我有一个数组保存几个文件的URL.例如:

var files = ['1.html', '2.html', '3.html'];
Run Code Online (Sandbox Code Playgroud)

我需要异步读取它们并将它们保存在名为cache(cache = {})的对象中.为此,我使用了代码:

for(var i = 0; i < files.length; i++){
    require('fs').readFile(files[i], 'utf8', function (error,data) {
        cache[files[i]]=data;
    });
}
Run Code Online (Sandbox Code Playgroud)

最后我得到了结果:

cache = { undefined : 'File 3 content' }
Run Code Online (Sandbox Code Playgroud)

我确实理解"循环结束后""readFile"会起作用并且它会失去它的范围.有没有办法解决这个或另一种方法从数组中读取文件并缓存它们?

Lin*_*iel 16

当你的回调readFile执行时,for循环已经完成.所以ifiles.lengthfiles[i]undefined.要缓解这种情况,您需要将变量包装在闭包中.最简单的方法是创建一个执行readFile调用的函数,并在循环中调用它:

function read(file) {
    require('fs').readFile(file, 'utf8', function (error,data) {
        cache[file]=data;
    });
}

for(var i = 0; i < files.length; i++){
    read(files[i]);
}
Run Code Online (Sandbox Code Playgroud)

为了更好的执行控制,您可能希望查看异步:

function readAsync(file, callback) {
    fs.readFile(file, 'utf8', callback);
}

async.map(files, readAsync, function(err, results) {
    // results = ['file 1 content', 'file 2 content', ...]
});
Run Code Online (Sandbox Code Playgroud)

编辑:使用辅助函数进行异步示例.