[nodejs]複数のファイルを非同期で読み込み、キャッシュする

1188 ワード

原文:http://stackoverflow.com/questions/9618142/asynchronously-reading-and-caching-multiple-files-in-nodejs
 
When your calback to  readFile executes、the for loop will already have finished.So  i will be  files.length and  files[i] will be  undefined.To mitigate this,you need to wrap the variables in a closure.The simplest way to this to create a function which does your  readFile call、and call that in the 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 execution control,you might want to look into async:
function readAsync(file, callback) {
    fs.readFile(file, 'utf8', callback);
}

async.map(files, readAsync, function(err, results) {
    // results = ['file 1 content', 'file 2 content', ...]
});
 
Edit: Made use of helper function for async example.