如何从nodejs中的phantomjs stdout中读取图像来提供它?

可能有些细节我缺less,因为光栅化脚本可以很好地独立运行,但是到目前为止,我还没有成功地从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); 

我想要做的就是用phantomjs将Base64编码的图像渲染成PNG,然后在nodejs中读取该图像,然后提供。

我究竟做错了什么?

我注意到你已经find了一个解决scheme。 为了其他可能降落在这里的人,这里的答案要简单得多:

PhantomJS:

 var base64 = page.renderBase64('PNG'); system.stdout.write(base64); phantom.exit(); 

节点(使用phantomjs-prebuilt):

 childProcess.execFile(binPath, childArgs, function(err, stdout, stderr) { var buf = new Buffer(stdout, 'base64'); fs.writeFile('test.png', buf); }