将一个命令的标准输出通过管道传输到另一个命令的标准输入,然后再传输到可写流

Piping stdout from one command into stdin for another, and then to a writable stream

使用 app.js 中的代码,我可以将 raspistill 命令的输出传输到 camera() 中 [=17] =] 到可写流。但是我想将输出传输到 convertresize() 中生成的命令,然后从 [= 传输标准输出而不是可写流36=]that 命令到可写流。

我尝试过的:

var streamOut = fs.createWriteStream('./image.jpg');
camerautil.camera().pipe(camerautil.resize(streamOut, 1, 1));

它抛出以下错误:

events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: Cannot pipe. Not readable.
    at WriteStream.Writable.pipe (_stream_writable.js:162:22)
    at Object.exports.resize (/home/pi/dev/app/camerautil.js:27:14)
    at Object.<anonymous> (/home/pi/dev/app/index3.js:5:37)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

这是我的(工作)代码:

app.js

var camerautil = require('./camerautil'),
    fs = require('fs');

var streamOut = fs.createWriteStream('./image.jpg');
camerautil.camera().pipe(streamOut);

camerautil.js

var spawn = require('child_process').spawn,
    Stream = require('stream');

exports.camera = function() {
    var child = spawn('raspistill', ['-w', 320, '-h', 240, '-n', '-t', 1, '-o', '-']);

    var stream = new Stream();

    child.stderr.on('data', stream.emit.bind(stream, 'error'));
    child.stdout.on('data', stream.emit.bind(stream, 'data'));
    child.stdout.on('end', stream.emit.bind(stream, 'end'));
    child.on('error', stream.emit.bind(stream, 'error'));

    return stream;
}

exports.resize = function(streamIn, width, height) {
    var child = spawn('convert', ['-', '-resize', width + 'x' + height, '-']);

    var stream = new Stream();

    child.stderr.on('data', stream.emit.bind(stream, 'error'));
    child.stdout.on('data', stream.emit.bind(stream, 'data'));
    child.stdout.on('end', stream.emit.bind(stream, 'end'));
    child.on('error', stream.emit.bind(stream, 'error'));

    streamIn.pipe(child.stdin);

    return stream;
}

我应该提到我是 Raspberry Pi 上的 运行 节点 v0.12.0。 raspistill命令用于使用相机模块拍照。 convert 命令是 ImageMagick 的一部分。

流式传输到 gm 模块(Imagemagick 的包装器)可能更简单。如果那将安装在 Raspberry PI 上,即

var gm = require('gm')
gm(camerautil.camera())
  .resize('100', '100')
  .stream('jpg')
  .pipe(streamOut)

https://github.com/aheckmann/gm#streams

经过一番摆弄,我找到了解决方案。

var camerautil = require('./camerautil'),
    fs = require('fs');

var streamOut = fs.createWriteStream('./image.jpg');
camerautil.resize(camerautil.camera(), 1, 1).pipe(streamOut);