NodeJs:为什么我的Writablestream在程序结束前没有关闭?

时间:2016-05-30 09:42:21

标签: node.js stream

我有一个NodeJS脚本,用于将JSON对象写入文件:

var reWriteCodes = function(arrayCodes, pathFileCodes, fs, typereWriteCodes, cb) {
  console.log("message : "+ typereWriteCodes);
  var codesStream = fs.createWriteStream(pathFileCodes, {'flags': 'w'});
  codesStream.on('finish', () => {
    console.log("the stream is closed")
    if (typereWriteCodes === 0) {
        cb();
    } 
  });
  var jsonToWrite = { "liste_codes" : arrayCodes};
  codesStream.write(JSON.stringify(jsonToWrite));
  codesStream.end();
}

这个函数被称为twiced(首先是typereWriteCodes = 0,然后是typereWriteCodes = 1,在回调函数中:cb),有两个不同的文件。

第一个电话结束正常,我的文件已保存,消息"流已关闭"显示在控制台中。但是在第二次调用(这是程序的最后一次操作)时,我的文件未正确保存(文件为空)并且消息"流已关闭"没有被触发。另外,我收到此消息:

  

events.js:141         扔掉//未处理的错误'事件         ^

     

错误:ENOENT:没有这样的文件或目录,打开''       在错误(本机)

我觉得应用程序在流可以正确结束前关闭...但我不知道我怎么能正确地做到这一点。你能帮帮我解决这个问题吗?任何帮助表示赞赏。

0 个答案:

没有答案