我需要连续运行两个命令,从同一个流中读取数据.

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]);
}

Request人对此抱怨

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

当然,将inputStream改为fs.createWriteStream也会产生同样的问题.

有没有一种方法可以在可读流完成管道后重用它?

推荐答案

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

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相关问答推荐

try 使用Puppeteer抓取Twitter时数组空

如何修复PayPal Node.js Webhook中Webhook签名验证失败?''

如何使用NodeJS处理来自请求的单个或多个文件?

Mongoose抱怨说,整数是数字,而不是整数

Node.js 连接在查询完成之前终止

如何从mongoose 对象内嵌套的数组中提取数组元素?

无法将示例 Node.js 应用程序部署到 AWS Elastic Beanstalk

在生产环境中,Nest实例启动时抛出不完整的导入错误

如何在 JavaScript 中显示多维数组中使用的一维数组的变量名?

我正在try 在公共目录中使用 Express.js 项目部署 Angular 静态构建

错误:无法为 /blog 收集页面数据并且在 object.fetch 处获取失败

node-gyp: "..\src\binding.cc: 没有这样的文件或目录"

JavaScript & Node - 将图像文件保存到服务器但无法查看

使用 firebase 函数 api 运行套接字(相同的端口创建问题)

如何监控 node.js 上的网络,类似于 chrome/firefox 开发者工具?

AngularJS +sails.js

Node.js 中空函数的简写

mongo 可以 upsert 数组数据吗?

大型项目的 NodeJS vs Play 框架

Google Firebase 错误(函数返回未定义、预期的 Promise 或值)