Node.js将流复制到文件中而不使用
给定解析传入流的函数:Node.js将流复制到文件中而不使用,node.js,stream,pipe,clone,Node.js,Stream,Pipe,Clone,给定解析传入流的函数: async onData(stream, callback) { const parsed = await simpleParser(stream) // Code handling parsed stream here // ... return callback() } 我正在寻找一种简单而安全的方法来“克隆”该流,这样我就可以将其保存到一个文件中,以便进行调试,而不会影响代码。这可能吗 假代码中的相同问题:我正试图做类似的事情。
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)
既然您仍然可以读取,为什么要克隆流again@0.sh效率。如果未调用
stream.close()
,则无需克隆stream@0.sh真的那么简单吗?我想我需要这样的东西(我的答案中没有包括这样的内容,以防止污染我将得到的答案)@0.sh实际上,你不能多次从同一个流中读取内容,因为第一次读取的速度会很快完成,流将关闭,所有其他读取都将不完整