【问题标题】:Node.js copy a stream into a file without consumingNode.js 将流复制到文件中而不消耗
【发布时间】:2019-06-18 07:35:08
【问题描述】:

给定一个函数解析传入的流:

async onData(stream, callback) {
    const parsed = await simpleParser(stream)

    // Code handling parsed stream here
    // ...

    return callback()
}

我正在寻找一种简单且安全的方法来“克隆”该流,以便将其保存到文件中以进行调试,而不会影响代码。这可能吗?

假代码中的相同问题:我正在尝试做这样的事情。显然,这是一个虚构的例子,是行不通的。

const fs = require('fs')
const wstream = fs.createWriteStream('debug.log')

async onData(stream, callback) {
    const debugStream = stream.clone(stream) // Fake code
    wstream.write(debugStream)

    const parsed = await simpleParser(stream)

    // Code handling parsed stream here
    // ...

    wstream.end()

    return callback()
}

【问题讨论】:

  • 你为什么要克隆流,因为你仍然可以再次读取它
  • @0.sh 效率。
  • 如果你没有调用stream.close(),那么就不需要克隆流
  • @0.sh 真的这么简单吗?我想我需要cloneable-readable 之类的东西(我没有在我的答案中包含它以防止污染我将得到的答案)
  • @0.sh 实际上你不能从同一个流中多次读取,只要第一次读取完成,流就会关闭,所有其他读取都将不完整

标签: node.js stream pipe clone


【解决方案1】:

不,您不能在不消费的情况下克隆可读流。但是,您可以通过管道传输两次,一次用于创建文件,另一次用于“克隆”。

代码如下:

let Readable = require('stream').Readable;
var stream = require('stream')

var s = new Readable()
s.push('beep')
s.push(null)  

var stream1 = s.pipe(new stream.PassThrough())
var stream2 = s.pipe(new stream.PassThrough())

// here use stream1 for creating file, and use stream2 just like s' clone stream
// I just print them out for a quick show
stream1.pipe(process.stdout)
stream2.pipe(process.stdout)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    相关资源
    最近更新 更多