Node.js 将流复制到文件中而不消耗 [英] Node.js copy a stream into a file without consuming

查看:17
本文介绍了Node.js 将流复制到文件中而不消耗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Given a function parses incoming streams:

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

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

    return callback()
}

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

I'm looking for a simple and safe way to 'clone' that stream, so I can save it to a file for debugging purposes, without affecting the code. Is this possible?

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

Same question in fake code: I'm trying to do something like this. Obviously, this is a made up example and doesn't work.

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()
}

推荐答案

不,不消耗就不能克隆可读流.但是,您可以通过管道传输两次,一次用于创建文件,另一次用于克隆".

No you can't clone a readable stream without consuming. However, you can pipe it twice, one for creating file and the other for 'clone'.

代码如下:

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 将流复制到文件中而不消耗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆