NodeJS readFile () restore file name

I repeat the array containing the file names. For each of them, I call readFile() . When the corresponding callback is called, I want to get the file name passed to readFile() as a parameter. It can be done?

Attached debugged code to better explain my intentions.

 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). }); } 
+6
source share
3 answers

You can also use forEach instead of the for loop:

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

You can do this using 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 each file name is saved as a function parameter and will not be affected by the loop that continues its iteration.

+8
source

You can also use Function.prototype.bind to add an argument. bind will return a new function that, when called, calls the original function with the [index] files as the first argument.

But I do not know if this is a good way to do this.

 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]) ); } 
0
source

Source: https://habr.com/ru/post/904759/


All Articles