Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

javascript - Writing multiple files a loop in Nodejs

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...