相关疑难解决方法(0)

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

我有一个数组保存几个文件的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"会起作用并且它会失去它的范围.有没有办法解决这个或另一种方法从数组中读取文件并缓存它们?

fs readfile node.js

4
推荐指数
1
解决办法
1万
查看次数

标签 统计

fs ×1

node.js ×1

readfile ×1