并行读取多个文件,并相应地将数据写入新文件node.js
Reading multiple files in parallel and writing the data in new files accordingly node.js
我正在尝试处理一个异步操作,该操作同时从一个文件夹读取多个文件,并在不同的文件夹中写入新文件。我读的文件是成对的。一个文件是数据模板,另一个是关于数据的。根据模板,我们处理来自相关数据文件的数据。我从这两个文件中获得的所有信息都被插入到一个对象中,我需要用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);
}
相关文章:
- 更改音频速度,然后另存为新文件
- webpack-dev-server 不会监视创建的新文件
- 如何使用javascript创建新的文件夹/文件
- 正在新文件中创建自定义任务
- 并行读取多个文件,并相应地将数据写入新文件node.js
- 将值插入JavaScript文件模板并生成新文件
- 如何创建新文件
- 将编辑的 SVG 文件另存为新文件或保存到数据库
- gulp-watch 插件不会在新文件上触发
- 监视目录中的新文件与javascript
- blueimp jQuery 文件上传新文件顺序
- 道场树中新文件夹结构中的问题
- 查看目录并尽快处理完整的新文件
- Multer 使用数据创建新文件夹
- 如何在多文件上传器中点击新文件浏览后保留旧文件
- 单击按钮将PHP变量发送到新文件
- 我需要将一组文件从它们的原始位置复制到一个新文件夹
- 使用Ajax从jQuery调用PHP脚本来创建一个新文件夹
- 添加新文件时在eclipse中刷新项目
- 如何通过计算文件夹中的文件数量来避免创建新文件