2

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

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@AmilaIddamalgoda Yes, fixed it. But it would have been easier if you had correctly indented your code to start with.
Yes mate!! my bad I fixed it already and this is working fine..Thnk you very much for pointing out the cause and giving me the solution..really appreciate it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.