将Buffer传递给ChildProcess Node.js [英] Pass Buffer to ChildProcess Node.js

查看:146
本文介绍了将Buffer传递给ChildProcess Node.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里我有Node.Js,我想在子流程中进行图像处理。

Here I have on Node.Js where I want to do Image Processing in a Sub Process.

正如您将看到的那样我将文件 image.jpg 并希望在子流程中将其写回 hello.jpg

As you will see I take the file image.jpg and want to write it back to hello.jpg in a subprocess:

var node = require('child_process').spawn('node',['-i']);
var fs = require('fs');

node.stdout.on('data',function(data) {
  var fs = require('fs');
    var gm = require('gm').subClass({ imageMagick: true });

    gm(data)
     .resize(500, 500)
     .toBuffer("jpg", function(err, buffer) {
      if (err) {
        console.log(err);
      }else{
        fs.writeFile("hello.jpg", buffer);  
      }
   });
});


var buffer = fs.readFileSync(__dirname + "/image.jpg");
node.stdin.write(buffer);

但是当我运行此文件时出现此错误:

However when I run this file I get this error:

[错误:流产生空缓冲区]

[Error: Stream yields empty buffer]

对我来说,似乎缓冲区未正确传递给子流程?
我有什么不对? 如何在子任务中运行图像处理。对我来说重要的是它不能从子进程中的文件中读取。因为我想再次读取一个文件,然后将缓冲区发送到几个进行图像转换的子进程。谢谢!

For me it seems like the buffer is not passed correctly to the subprocess? What do I wrong? What can I do to run Image Processing in a subtask. For me its important that Its not read from a file in the subprocess. Because I want to read one File again and then send the buffer to several subprocesses that do Image Transformations. Thanks!

推荐答案

您没有在子流程中做任何工作。它只是 node -i 而没有别的。所有的图像处理都在主进程中进行。

You are not doing any work in a subprocess. It is just node -i and nothing else. All your image processing happens in the main process.

要修复它,你可以实际运行另一个Node进程并给它一些脚本来执行,比如 worker.js

To fix it, you can actually run another Node process and give it some script to execute, say worker.js:

process.stdin.on('data',function(data) {
  var fs = require('fs');
    var gm = require('gm').subClass({ imageMagick: true });

    gm(data)
     .resize(500, 500)
     .toBuffer("jpg", function(err, buffer) {
      if (err) {
    console.log(err);
      }else{
    fs.writeFile("hello.jpg", buffer);
      }
   });
});

然后你将从主脚本创建一个子流程:

Then you would create a subprocess from your main script:

var node = require('child_process').spawn('node', ['worker.js']);
var fs = require('fs');

var buffer = fs.readFileSync(__dirname + "/image.jpg");
node.stdin.end(buffer);

请注意,我使用 node.stdin.end 在最后一行终止工人。

Note that I used node.stdin.end in the last line to terminate the worker.

看看集群模块。

这篇关于将Buffer传递给ChildProcess Node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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