gpt4 book ai didi

javascript - Node.js 将相同的可读流输送到多个(可写)目标中

转载 作者:IT老高 更新时间:2023-10-28 21:50:47 26 4
gpt4 key购买 nike

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

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 当然会产生相同的问题。我不想写入文件,但以某种方式重用 request 产生的流(或任何其他方式)。

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

最佳答案

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

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

关于javascript - Node.js 将相同的可读流输送到多个(可写)目标中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19553837/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com