Node.js无需消耗就将流复制到文件中

问题描述 投票:1回答:1

给出一个函数来解析输入流:

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()
}
node.js stream pipe clone
1个回答
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)

© www.soinside.com 2019 - 2024. All rights reserved.