Writing multiple files a loop in Nodejs

淺唱寂寞╮ 提交于 2019-11-29 12:21:37

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.

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