读取多个文件并行,写在新文件中的数据相应的node.js(Reading multiple file

2019-10-29 03:15发布

我想处理,上面写着在同一时间从一个文件夹中的多个文件,并在不同的文件夹写入新的一个异步操作。 我读的文件是通过对。 一个文件是数据模板,另一个是关于数据。 根据模板,我们处理来自相关数据文件中的数据。 我从两个文件得到的所有信息被插入到一个对象,我需要在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个文件,所以两个模板文件和两个相关的数据文件,它坠毁。 因此,我相信我有回调的一个问题...也许有人可以帮我看着办吧! 提前致谢 !

Answer 1:

它发生,因为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);
}


文章来源: Reading multiple files in parallel and writing the data in new files accordingly node.js