1

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?

TrippLamb
  • 1,422
  • 13
  • 24

2 Answers2

2

Try wrapping it in a self executing anonymous function:

fs = require('fs');

for(var i = 0; i < 5; i++){
    (function(i) {
        fs.readFile(filePath, function(err, data){
            console.log(i);
        });
    })(i)
}

Also, keep in mind this approach won't scale. If you try a for loop to 1000 for instance, it will try to make all 1000 readFile calls concurrently. You're better off using something like the async library to make sure you're not running too many IO operations concurrently.

Timothy Strimple
  • 22,920
  • 6
  • 69
  • 76
2

The easiest way is to use an immediately-invoked function expression (IIFE):

fs = require('fs');

for(var i = 0; i < 5; i++){
    (function(i){
        fs.readFile(filePath, function(err, data){
            console.log(i);
        });
    })(i);
}

This "captures" the value of i at each iteration inside an anonymous closure.

Ethan Brown
  • 26,892
  • 4
  • 80
  • 92