I am iterating over an array which contains filenames. For each of them, I invoke readFile()
. When the corresponding callback is invoked, I wish to retrieve the filename passed to readFile()
as a parameter. Can it be done?
Enclosed a snipped code to better explain my intention.
var fs = require("fs");
var files = ["first.txt", "second.txt"];
for (var index in files) {
fs.readFile(files[index], function(err, data) {
//var filename = files[index];
// If I am not mistaken, readFile() is asynchronous. Hence, when its
// callback is invoked, files[index] may correspond to a different file.
// (the index had a progression).
});
}
You could also use
forEach
instead of afor
loop:You can do that using a closure:
Now every file name is saved as a function's parameter and won't be affected by the loop continuing its iteration.
You can also use
Function.prototype.bind
to prepend an argument.bind
will return a new function that, when called, calls the original function with files[index] as the first argument.But no idea if this is a good way to do it.