NodeJS readFile() retrieve filename

跟風遠走 提交于 2019-12-06 01:07:47

问题


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).
    });

}

回答1:


You could also use forEach instead of a for loop:

files.forEach(function (file){
  fs.readFile(file, function (err, data){
    console.log("Reading %s...", file)
  })
})



回答2:


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.




回答3:


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.

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])
    );

}


来源:https://stackoverflow.com/questions/8681519/nodejs-readfile-retrieve-filename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!