gpt4 book ai didi

javascript - 并行读取多个文件并相应地将数据写入新文件中node.js

转载 作者:行者123 更新时间:2023-12-03 10:45:28 25 4
gpt4 key购买 nike

我正在尝试处理一个异步操作,该操作同时从一个文件夹读取多个文件并在不同的文件夹中写入新文件。我读的文件是成对的。一个文件是数据模板,另一个文件是关于数据的。根据模板,我们处理相关数据文件中的数据。我从这两个文件中获得的所有信息都被插入到一个对象中,我需要将其以 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com