I feel like I must be missing something obvious, but I can't seem to find it.
In nodejs how can I pass additional arguments into a callback function?
fs = require('fs');
for(var i = 0; i < 5; i++){
fs.readFile(filePath, function(err, data){
console.log(i);
});
}
doing it this way you usually get a bunch of 4's written to the screen. I understand why that is happening. It is happening because that is the value of 'i' by the time it gets to that part of the code for all the callbacks. This doesn't work either:
fs = require('fs');
for(var i = 0; i < 5; i++){
fs.readFile(filePath, callback(err, data, i));
}
function callback(err, data, i){
console.log(i);
}
as 'err' and 'data' are undefined. I also understand why that is the case.
This works for 'i' but then I lose the err and data values that I need.
fs = require('fs');
for(var i = 0; i < 5; i++){
fs.readFile(filePath, callback(i))
}
function callback(num){
console.log(num);
}
How do I solve this?