Reputation: 4296
Hi I'm using a for each loop to in nodejs script to write multiple files to a local location.For the courseTitleArray I'm using "Biology 101,ruby" and I can write one file successfully but not the both.Please help me out.
Here is my code so far
for (var value in CourseTitleArray) {
console.log( "Course Title " + CourseTitleArray[value]);
var newImageLocation = path.join(__dirname, 'app/img/courseImages', CourseTitleArray[value] + ".png");
fs.readFile(image.path, function(err, data) {
fs.writeFile(newImageLocation, data, function(err) {
console.log(CourseTitleArray[value] + " was created successfully");
});
});
console.log("Loop executed " + value);
}
And in the console I get following logs.
Course Title Biology 101
Loop executed 0
Course Title ruby
Loop executed 1
ruby was created successfully
ruby was created successfully
It seems the loops working fine and as in the log I can see both titles. But when it's writing "Biology 101,ruby" have executed twice .
Can anybody help me out with this? Thanks
Upvotes: 2
Views: 3432
Reputation: 382464
The problem you have is that your callback is called when the loop is finished, so value
has changed.
A solution is to use a closure to store the value of value
:
for (var value in CourseTitleArray) {
(function(value){
console.log( "Course Title " + CourseTitleArray[value]);
var newImageLocation = path.join(__dirname, 'app/img/courseImages', CourseTitleArray[value] + ".png");
fs.readFile(image.path, function(err, data) {
fs.writeFile(newImageLocation, data, function(err) {
console.log(CourseTitleArray[value] + " was created successfully");
});
});
console.log("Loop executed " + value);
})(value);
}
Note that it's not clear what you mean with your "Loop executed" log : when you log, the writing hasn't yet occurred.
Upvotes: 5