在Node中从子进程发送数据到父进程

时间:2017-06-09 14:10:42

标签: javascript node.js canvas process child-process

我有一个Node应用程序,它使用Node Canvas创建画布然后转换为PNG。我的代码是:

// create the canvas and draw stuff on it up here

// convert to a base64 string
var buf = canvas.toBuffer();

var graph = buf.toString('base64');

var data = JSON.stringify({
    graph: graph
});

var headers = {
    'Content-Type': 'image/png'
};

res.writeHead(200, headers);
res.end(data);

一切正常。现在我想把它变成一个子进程。所以在我的父进程中:

// in parent process, start the child process
var self = this;
var spawn = require('child_process').spawn;

var child = spawn(process.execPath, ['/home/mark/Programming/myapp/app/child_process_scripts/createDotPlotGraph.js']);

child.stdout.on('data', function(buf){

    console.log('buf is ', buff);

    var graph = buf.toString('base64');

    console.log('graph is ', graph);

    var data = JSON.stringify({
        graph: graph
    });

    var headers = {
        'Content-Type': 'image/png'
    };

    res.writeHead(200, headers);
    res.end(data);

    child.kill();
});

在我的孩子过程中,我这样做:

 // in child process, output the buffer
  var buf = canvas.toBuffer();
  console.log(buf);

但是,它无法正常工作,发送回前端的base64字符串似乎已损坏。

父级bufconsole.log的输出为:

buf is  <Buffer 3c 42 75 66 66 65 72 20 38 39 20 35 30 20 34 65 20 34 37 20 30 64 20 30 61 20 31 61 20 30 61 20 30 30 20 30 30 20 30 30 20 30 64 20 34 39 20 34 38 20 ... >

父母graphconsole.log的输出为:

graph is  PEJ1ZmZlciA4OSA1MCA0ZSA0NyAwZCAwYSAxYSAwYSAwMCAwMCAwMCAwZCA0OSA0OCA0NCA1MiAwMCAwMCAwMSA2NCAwMCAwMCAwMSA2NCAwOCAwNiAwMCAwMCAwMCAxNyAxYiA0MSAyMCAwMCAwMCAwMCAwNiA2MiA0YiA0NyA0NCAwMCBmZiAwMCBmZiAwMCBmZiBhMCBiZCBhNyAuLi4gPgo=

看起来在向arent进程发送数据时,它会将其更改为缓冲区,因为在孩子中即使我这样做了:

console.log('test string');

父级bufconsole.log的输出为:

buf is  <Buffer 74 65 73 74 20 73 74 72 69 6e 67 0a>

我本以为&#34;测试字符串&#34;。所以看起来画布的缓冲区本身就变成了缓冲区....任何想法?

0 个答案:

没有答案