I have an array which keeps URL of several files. For example:
var files = ['1.html', '2.html', '3.html'];
I need to read them asynchronously and save them in an object named cache (cache = {}).
To do this I used the code:
for(var i = 0; i < files.length; i++){
require('fs').readFile(files[i], 'utf8', function (error,data) {
cache[files[i]]=data;
});
}
In the end I have the result:
cache = { undefined : 'File 3 content' }
I do understand that the “readFile” acts after the loop is ended and it looses it’s scope. Is there a way to fix this or another method to read files from an array and cache them?
When your callback to
readFileexecutes, the for loop will already have finished. Soiwill befiles.lengthandfiles[i]will beundefined. To mitigate this, you need to wrap the variables in a closure. The simplest way to do this is to create a function which does yourreadFilecall, and call that in the loop:For even better execution control, you might want to look into async:
Edit: Made use of helper function for async example.