Writing multiple files a loop in Nodejs

六眼飞鱼酱① 提交于 2019-11-28 05:46:04

问题


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:


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.



来源:https://stackoverflow.com/questions/24505416/writing-multiple-files-a-loop-in-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!