在Nodejs中编写多个文件循环 [英] Writing multiple files a loop in Nodejs

查看:419
本文介绍了在Nodejs中编写多个文件循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我在nodejs脚本中使用每个循环来将多个文件写入本地位置。对于courseTitleArray,我正在使用Biology 101,ruby,我可以写一个文件成功不是两者。请帮助我。

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 

似乎循环工作正常并且在日志中我可以看两个标题。
但是当它写生物学101,红宝石已经执行了两次。

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

推荐答案

你遇到的问题是你的回调在循环结束时被调用,所以已更改。

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.

这篇关于在Nodejs中编写多个文件循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆