- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试处理一个异步操作,该操作同时从一个文件夹读取多个文件并在不同的文件夹中写入新文件。我读的文件是成对的。一个文件是数据模板,另一个文件是关于数据的。根据模板,我们处理相关数据文件中的数据。我从这两个文件中获得的所有信息都被插入到一个对象中,我需要将其以 JSON 格式写入新文件中。如果只有一对这些文件(1 个模板和 1 个数据),下面的代码可以完美运行:
for(var i = 0; i < folderFiles.length; i++)
{
var objectToWrite = new objectToWrite();
var templatefileName = folderFiles[i].toString();
//Reading the Template File
fs.readFile(baseTemplate_dir + folderFiles[i],{ encoding: "utf8"},function(err, data)
{
if(err) throw err;
//Here I'm manipulating template data
//Now I want to read to data according to template read above
fs.readFile(baseData_dir + folderFiles[i],{ encoding: "utf8"},function(err, data)
{
if(err) throw err;
//Here I'm manipulating the data
//Once I've got the template data and the data into my object objectToWrite, I'm writing it in json in a file
fs.writeFile(baseOut_dir + folderFiles[i], JSON.stringify(objectToWrite ),{ encoding: 'utf8' }, function (err)
{
if(err) throw err;
console.log("File written and saved !");
}
}
}
}
由于我有 4 个文件,即两个模板文件和两个相关数据文件,所以它崩溃了。所以我相信我的回调有问题......也许有人可以帮助我解决这个问题!提前致谢!
最佳答案
发生这种情况是因为 readFile
是异步的,所以 for
循环不会等待它执行并继续下一次迭代,最终完成所有迭代速度非常快,因此当执行 readFile 回调时,folderFiles[i] 将包含最后一个文件夹的名称 => 所有回调将仅操作最后一个文件夹名称。解决方案是将所有这些东西移到循环之外的单独函数中,这样闭包就会派上用场。
function combineFiles(objectToWrite, templatefileName) {
//Reading the Template File
fs.readFile(baseTemplate_dir + templatefileName,{ encoding: "utf8"},function(err, data)
{
if(err) throw err;
//Here I'm manipulating template data
//Now I want to read to data according to template read above
fs.readFile(baseData_dir + templatefileName,{ encoding: "utf8"},function(err, data)
{
if(err) throw err;
//Here I'm manipulating the data
//Once I've got the template data and the data into my object objectToWrite, I'm writing it in json in a file
fs.writeFile(baseOut_dir + templatefileName, JSON.stringify(objectToWrite ),{ encoding: 'utf8' }, function (err)
{
if(err) throw err;
console.log("File written and saved !");
}
}
}
}
for(var i = 0; i < folderFiles.length; i++)
{
var objectToWrite = new objectToWrite();
var templatefileName = folderFiles[i].toString();
combineFiles(objectToWrite, templatefileName);
}
关于javascript - 并行读取多个文件并相应地将数据写入新文件中node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28581117/
我在 Java 中遇到异常处理问题,这是我的代码。当我尝试运行此行时出现编译器错误:throw new MojException("Bledne dane");。错误是: exception MojE
我刚刚开始学习asp.net。在你们的支持下,我希望我能从这个论坛学到更多东西。 我的问题是, 我在 asp.net 页面中有一个 TabContainer1,因为每个选项卡面板中有多个类似 (60)
我是一名优秀的程序员,十分优秀!