繁体   English   中英

并行读取多个文件,并相应地将数据写入新文件中。

[英]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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM