我可能遗漏了一些细节,因为光栅化脚本独立工作得很好,但到目前为止我还没有成功地从 NodeJS 读取它的输出。
这是 NodeJS 部分:
var http = require('http');
var qs = require('querystring');
var fs = require('fs');
var spawn = require('child_process').spawn;
var SCRIPT = fs.readFileSync('./script.js', { encoding: 'utf8' });
http.createServer(function (request, response) {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var postData = qs.parse(body);
var phantomOut = '';
var phantom = spawn('phantomjs');
phantom.stdout.on('data', function (buf) {
phantomOut += buf;
});
phantom.on('exit', function (code) {
response.writeHead(200, {
'Content-Type': 'image/png'
});
response.end(phantomOut);
});
phantom.stdin.setEncoding('utf8');
phantom.stdin.write( SCRIPT.replace('(#imageData)', postData.imageData) );
});
}).listen(1337, '127.0.0.1');
这是由 PhantomJS 执行的“script.js”:
var page = require('webpage').create();
page.content = '<img src="(#imageData)">';
window.setTimeout(function () {
page.render('/dev/stdout', { format: 'png' });
phantom.exit();
}, 1);
我想做的是将 Base64 编码的图像渲染为 PNG,使用 phantomjs 到标准输出,在 NodeJS 中读取该图像,然后提供它。
我究竟做错了什么?