Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS readFile() retrieve filename

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

}
like image 660
MrIzik Avatar asked Dec 30 '11 16:12

MrIzik


People also ask

Does readFile return anything?

readFile. Returns the contents of the file named filename. If encoding is specified then this function returns a string. Otherwise it returns a buffer.

How do I fetch a file in node JS?

Downloading a file using node js can be done using inbuilt packages or with third party libraries. GET method is used on HTTPS to fetch the file which is to be downloaded. createWriteStream() is a method that is used to create a writable stream and receives only one argument, the location where the file is to be saved.

What does readFile do in Nodejs?

The fs.readFile() method is used to read files on your computer.


1 Answers

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.

like image 55
Felix Loether Avatar answered Sep 30 '22 13:09

Felix Loether