Node.js 将相同的可读流传送到多个(可写)目标中 [英] Node.js Piping the same readable stream into multiple (writable) targets

查看:24
本文介绍了Node.js 将相同的可读流传送到多个(可写)目标中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要连续运行两个需要从同一个流中读取数据的命令.将一个流通过管道传输到另一个流后,缓冲区被清空,因此我无法再次从该流中读取数据,因此这不起作用:

I need to run two commands in series that need to read data from the same stream. After piping a stream into another the buffer is emptied so i can't read data from that stream again so this doesn't work:

var spawn = require('child_process').spawn;
var fs = require('fs');
var request = require('request');

var inputStream = request('http://placehold.it/640x360');
var identify = spawn('identify',['-']);

inputStream.pipe(identify.stdin);

var chunks = [];
identify.stdout.on('data',function(chunk) {
  chunks.push(chunk);
});

identify.stdout.on('end',function() {
  var size = getSize(Buffer.concat(chunks)); //width
  var convert = spawn('convert',['-','-scale',size * 0.5,'png:-']);
  inputStream.pipe(convert.stdin);
  convert.stdout.pipe(fs.createWriteStream('half.png'));
});

function getSize(buffer){
  return parseInt(buffer.toString().split(' ')[2].split('x')[0]);
}

请求对此提出投诉

Error: You cannot pipe after data has been emitted from the response.

并将 inputStream 更改为 fs.createWriteStream 当然会产生相同的问题.我不想写入文件,而是以某种方式重用请求产生的流(或任何其他与此相关的流).

and changing the inputStream to fs.createWriteStream yields the same issue of course. I don't want to write into a file but reuse in some way the stream that request produces (or any other for that matter).

有没有办法在完成管道后重用可读流?完成上述示例的最佳方法是什么?

Is there a way to reuse a readable stream once it finishes piping? What would be the best way to accomplish something like the above example?

推荐答案

您必须通过管道将流传输到两个流来创建流的副本.您可以使用 PassThrough 流创建一个简单的流,它只是将输入传递给输出.

You have to create duplicate of the stream by piping it to two streams. You can create a simple stream with a PassThrough stream, it simply passes the input to the output.

const spawn = require('child_process').spawn;
const PassThrough = require('stream').PassThrough;

const a = spawn('echo', ['hi user']);
const b = new PassThrough();
const c = new PassThrough();

a.stdout.pipe(b);
a.stdout.pipe(c);

let count = 0;
b.on('data', function (chunk) {
  count += chunk.length;
});
b.on('end', function () {
  console.log(count);
  c.pipe(process.stdout);
});

输出:

8
hi user

这篇关于Node.js 将相同的可读流传送到多个(可写)目标中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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