[英]How to read an image from phantomjs stdout in nodejs to serve it?
There's probably some detail that I'm missing, because the rasterization script works fine standalone, but I haven't been successful reading its output from NodeJS so far. 我可能缺少一些细节,因为光栅化脚本可以很好地独立工作,但到目前为止我还没有成功地从NodeJS读取它的输出。
Here's the NodeJS part: 这是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');
And here's the 'script.js' that is executed by PhantomJS: 这是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);
What I'd like to do is to render Base64 encoded image to PNG with phantomjs to stdout, read that image in nodejs and then serve it. 我想做的是将带有phantomjs的Base64编码图像渲染到PNG到stdout,在nodejs中读取该图像然后提供它。
What am I doing wrong? 我究竟做错了什么?
I noticed that you have found a solution. 我注意到你找到了解决方案。 Just for the sake of others who may land here, here is a far easier answer: 只是为了可能降落在这里的其他人,这里有一个更容易的答案:
PhantomJS: PhantomJS:
var base64 = page.renderBase64('PNG');
system.stdout.write(base64);
phantom.exit();
Node (using phantomjs-prebuilt): 节点(使用phantomjs-prebuilt):
childProcess.execFile(binPath, childArgs, function(err, stdout, stderr) {
var buf = new Buffer(stdout, 'base64');
fs.writeFile('test.png', buf);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.