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

Reading multiple files in parallel and writing the data in new files accordingly node.js

本文关键字:文件 新文件 node 数据 js 读取 并行      更新时间:2023-12-25

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