【问题标题】:What can make a writeStream to emit close without writing to file?什么可以使 writeStream 发出关闭而不写入文件?
【发布时间】:2019-09-12 23:09:59
【问题描述】:

我想将文件的夹头合并到另一个文件,但 writeStream 正在发出关闭而不将 readStream 内容写入或附加到输出文件。

我有一个带有 for-of 循​​环的 async 函数,该循环遍历数组并在循环内我创建了一个 writableStream 带有标志 write truncate/write w flag if iteration index is 0 else append @987654326 @ 然后创建一个 readStream 然后将其通过管道传输到 writeStream


 async function mergeBlocks(op) {
  for (const [index, block] of op.blockObjects.entries()) {
    const flags = index === 0? 'w' : 'a'
    const w = createWriteStream(op.output, { start: block.start, flags }),
      r = createReadStream(block.path, { start: block.start, end: block.end })
    console.log(index)
    r.pipe(w)
    await new Promise(res =>
      w.on('finish', () => {
        console.log('close')
        res()
      })
    )
  }
}

但它只写入第一个块并关闭writeStream,而不写入输出文件以供其他迭代使用。请问我做错了什么?

编辑检查下面的答案。

【问题讨论】:

  • 为什么不创建一个单独的 writeStream,并在循环中继续追加它?如果您当前的代码产生错误消息,请将它们添加到您的问题中。
  • @ChrisG 这就是问题所在,没有错误消息,但让我们再试一次 writeStream。

标签: javascript node.js node-streams


【解决方案1】:

startend 我设置为 createReadStream 选项不是必需的位置解释了为什么只写入到文件的第一个块,而其他块只是空内容。 至于代码,我最终使用了 promisify stream.pipeline,这进一步简化了我的代码。


async function mergeBlocks() {
  for (const [index, block] of op.blockObjects.entries()) {
    await pipeline(
      createReadStream(join(block.bucket, block.hash)),
      createWriteStream(op.output, { flags: index === 0 ? 'w' : 'a', start: block.start })
    )
  }
}

【讨论】:

    猜你喜欢
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    • 2017-12-20
    • 2018-09-18
    相关资源
    最近更新 更多