When your readFile response is executed, the for loop will already be completed. Thus, i will be files.length , and files[i] will be undefined . To mitigate this, you need to wrap the variables in closure. The easiest way to do this is to create a function that executes your readFile call, and call it in a loop:
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]); }
For even better control over execution, you can look at async :
function readAsync(file, callback) { fs.readFile(file, 'utf8', callback); } async.map(files, readAsync, function(err, results) {
Edit: Use a helper function for the async example.
source share