[英]NodeJS readFile() retrieve filename
I am iterating over an array which contains filenames. 我正在迭代一个包含文件名的数组。 For each of them, I invoke
readFile()
. 对于它们中的每一个,我调用
readFile()
。 When the corresponding callback is invoked, I wish to retrieve the filename passed to readFile()
as a parameter. 当调用相应的回调时,我希望检索传递给
readFile()
的文件名作为参数。 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 can do that using a closure: 你可以使用一个闭包来做到这一点:
for (var index in files) {
(function (filename) {
fs.readFile(filename, function(err, data) {
// You can use 'filename' here as well.
console.log(filename);
});
}(files[index]));
}
Now every file name is saved as a function's parameter and won't be affected by the loop continuing its iteration. 现在,每个文件名都保存为函数的参数,并且不会受到循环继续其迭代的影响。
You could also use forEach
instead of a for
loop: 您也可以使用
forEach
而不是for
循环:
files.forEach(function (file){
fs.readFile(file, function (err, data){
console.log("Reading %s...", file)
})
})
You can also use Function.prototype.bind
to prepend an argument. 您还可以使用
Function.prototype.bind
来添加参数。 bind
will return a new function that, when called, calls the original function with files[index] as the first argument. bind
将返回一个新函数,当调用它时,调用原始函数,文件[index]作为第一个参数。
But no idea if this is a good way to do it. 但不知道这是否是一个很好的方法。
var fs = require("fs");
var files = {"first.txt", "second.txt"};
for (var index in files) {
fs.readFile(files[index],
(function(filename, err, data) {
//filename
}).bind(null, files[index])
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.