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

查看:41
本文介绍了从 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);
});

我希望它相当于命令行 convert ./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');
});

另一个示例,使用 Express 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天全站免登陆