给定一个解析传入流的函数:
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()
}
最佳答案
不,您无法在不消耗的情况下克隆可读流。但是,您可以对其进行两次管道传输,一次用于创建文件,另一次用于“克隆”。
代码如下:
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)
关于Node.js 将流复制到文件中而不消耗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54348804/