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).
});
}
readFile. Returns the contents of the file named filename. If encoding is specified then this function returns a string. Otherwise it returns a buffer.
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.
The fs.readFile() method is used to read files on your computer.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With