5

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.

Here's the NodeJS part:

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:

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.

What am I doing wrong?

Vitaly
  • 4,358
  • 7
  • 47
  • 59
  • would be nice if anybody would consider to answer this. in phantomjs lots of node.js stuff just doesn't work. including fs.readFileSync() – holms Apr 18 '14 at 16:27
  • If you are wondering, I ended up creating a temporary script with the , spawning phantomjs as a process and passing the path to the script as a parameter. Then reading the generated image when phantomjs process exists in nodejs, serving it and removing both the script and the image as soon as the latter is served. Appears to work very well. – Vitaly Apr 21 '14 at 22:23
  • @Vitaly is this related: http://stackoverflow.com/questions/19512983/phantomjs-pdf-to-stdout?rq=1 ? – edin-m Dec 11 '15 at 23:06
  • @EdinM. Thank you. I have ended up saving a generated script to disk before running it with Phantom. – Vitaly Dec 12 '15 at 23:48

1 Answers1

3

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:

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

Node (using phantomjs-prebuilt):

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