When I run the code below, it always print 5, is there any way to save state? make it print 0, 1, 2, 3, 4?
for(var i=0; i<5; i++){
fs.readFile("./test.txt", "utf8", function(err, data){
console.log(i);
});
}
When I run the code below, it always print 5, is there any way to save state? make it print 0, 1, 2, 3, 4?
for(var i=0; i<5; i++){
fs.readFile("./test.txt", "utf8", function(err, data){
console.log(i);
});
}
You can create a closure (useful for this cases):
for(var i=0; i<5; i++){
fs.readFile("./test.txt", "utf8", function(i) {
return function(err, data) {
console.log(i);
};
}(i));
}
You create an anonymous function, but with i in the scope. Note that you can get the numbers in a different order, as reading a file is an asynchronous operation:
> 0
1
2
3
4
or:
> 0
2
1
3
4
You could use promises for example.
var Q = require('q');
var fs = require('fs');
var readFile = function(i) {
var deferred = Q.defer();
fs.readFile("./test.txt", "utf8", function(err, data) {
deferred.resolve(i);
});
return deferred.promise;
};
for (var i = 0; i < 5; i++) {
readFile(i).then(function(result) {
console.log(result);
});
}