【问题标题】:Do I need await fs.createWriteStream in pipe method in node?我需要在节点的管道方法中等待 fs.createWriteStream 吗?
【发布时间】:2018-03-26 22:03:11
【问题描述】:

我很困惑使用管道处理写入流是否同步,因为我发现了一个关于callback to handle completion of pipe的问题

我只是想确保写入流在其他人之前完成,例如fs.rename,所以我承诺它,代码如下:

(async function () {
  await promiseTempStream({oldPath, makeRegex, replaceFn, replaceObj, tempPath})
  await rename(tempPath, oldPath)
  function promiseTempStream({oldPath, makeRegex, replaceFn, replaceObj, tempPath}) {
  return new Promise((res, rej) => {
    const writable = fs.createWriteStream(tempPath)
    fs.createReadStream(oldPath, 'utf8')       
      .pipe(replaceStream(makeRegex ,replaceFn.bind(this, replaceObj), {maxMatchLen: 5000}))
    .pipe(writable)
    writable
      .on('error', (err) => {rej(err)})
      .on('finish', res)
    })
}
}())

它有效,但我在阅读pipe doc 后感到困惑,因为它说

默认情况下,当源可读流发出'end'时,在目标可写流上调用stream.end(),因此目标不再可写。

所以我只需要

await fs.createReadStream(oldPath, 'utf8')
.pipe(replaceStream(makeRegex ,replaceFn.bind(this, replaceObj), {maxMatchLen: 5000}))
.pipe(fs.createWriteStream(tempPath))
await rename(tempPath, oldPath)

或者只是

fs.createReadStream(oldPath, 'utf8')
.pipe(replaceStream(makeRegex ,replaceFn.bind(this, replaceObj), {maxMatchLen: 5000}))
.pipe(fs.createWriteStream(tempPath))
await rename(tempPath, oldPath)

哪种方法是正确的?非常感谢

【问题讨论】:

  • 这不是一个承诺,所以你不能 await它。

标签: node.js async-await pipe


【解决方案1】:

您需要等待 tempPath 流上的 finish 事件。所以你可以做类似的事情

async function createTheFile() {
return new Promise<void>(resolve => {
    let a = replaceStream(makeRegex, replaceFn.bind(this, replaceObj), { maxMatchLen: 5000 });
    let b = fs.createWriteStream(tempPath);
    fs.createReadStream(oldPath, 'utf8').pipe(a).pipe(b);
    b.on('finish', resolve);
}
}

await createTheFile();
rename(tempPath, oldPath);

基本上,我们在这里创建了一个 Promise,当我们完成对 tempFile 的写入时,它会解析。在继续之前,您需要等待该承诺。

但是,如果您还像Error handling with node.js streams 中提到的那样在流中添加一些错误处理代码,那就太好了

【讨论】:

  • b.on('finish', resolve);或 b.on('close', resolve); ?
  • Stream 在完成写入时会发出“finish”,但流可能尚未关闭。所以“关闭”是流关闭时的最后阶段。
猜你喜欢
  • 2017-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-16
  • 1970-01-01
  • 1970-01-01
  • 2022-11-21
相关资源
最近更新 更多