在Node.js的一个子进程读取二进制数据 [英] Reading binary data from a child process in Node.js

查看:167
本文介绍了在Node.js的一个子进程读取二进制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当试图从一个ImageMagick的子进程读取数据的Node.js,它出来损坏。

When trying to read data in Node.js from an ImageMagick child process, it comes out corrupted.

一个简单的测试情况是以下内容:

A simple test case would be the following:

var fs = require('fs');
var exec = require('child_process').exec;

var cmd = 'convert ./test.jpg -';
exec(cmd, {encoding: 'binary', maxBuffer: 5000*1024}, function(error, stdout) {
  fs.writeFileSync('test2.jpg', stdout);
});

我希望这是命令行转换./test.jpg相当于 - > test2.jpg ,做正确写入二进制文件。

I would expect that to be the equivalent of the command line convert ./test.jpg - > test2.jpg that does write the binary file correctly.

最初有一个与maxBuffer选项太小并导致截短的文件的问题。增加在此之后,该文件现在看来稍大于预期,仍然损坏。
从标准输出的数据需要通过HTTP发送。

Originally there was a problem with the maxBuffer option being too small and resulting in a truncated file. After increasing that, the file now appears slightly larger than expected and still corrupted. The data from stdout is required to send over HTTP.

什么是阅读来自ImageMagick标准输出这个数据的正确方法是什么?

What would be the correct way to read this data from the ImageMagick stdout?

推荐答案

有两个问题与最初的方法。

There were two problems with the initial approach.


  1. 该maxBuffer需要足够高,能够处理从子进程整个响应。

  1. The maxBuffer needs to be high enough to handle the whole response from the child process.

二进制编码需要正确设置无处不在。

Binary encoding needs to be properly set everywhere.

一个完整的工作的例子是以下内容:

A full working example would be the following:

var fs = require('fs');
var exec = require('child_process').exec;

var cmd = 'convert ./test.jpg -';
exec(cmd, {encoding: 'binary', maxBuffer: 5000*1024}, function(error, stdout) {
  fs.writeFileSync('test2.jpg', stdout, 'binary');
});

另外一个例子,在使用防爆preSS Web框架HTTP响应发送数据,将是这样的:

Another example, sending the data in an HTTP response using the Express web framework, would like this:

var express = require('express');
var app = express.createServer();

app.get('/myfile', function(req, res) {
  var cmd = 'convert ./test.jpg -';
  exec(cmd, {encoding: 'binary', maxBuffer: 5000*1024}, function(error, stdout) {
     res.send(new Buffer(stdout, 'binary'));
  });
});

这篇关于在Node.js的一个子进程读取二进制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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