Am using Prawn PDF in a node.js webapp to generate PDF on the fly and send it back to the user. It works fine as long as there are no images in the PDF doc. The moment I include an image (png or jpeg) in the pdf, the spawned node child process never gets the 'exit' message.
The same ruby script outputs a pdf with images as expected when run in the shell. Somehow the image data seems to get messed up when sent over stdout! Do I have to escape it?
Thanks, mano
var spawn = require('child_process').spawn;
var child = spawn('ruby', ['print_scripts/print.rb', doc_id]);
var pdf = '';
child.stdout.on('data', function(data){
    if(data.toString() != 'ERROR'){
    pdf += data;
    }
});
child.on('exit', function(code){
    res.setHeader('Content-Type', 'application/pdf');
    if(code == 0){
    res.send(pdf);
    }
});
				
				In a simple test I did, exit is called even before data is called. That's probably related to this notice: "Note that the child process stdio streams might still be open." (which could mean that there's still data left in internal buffers that needs to be read).
When you're not using images, the output might be small enough to fit in a single buffer so the problem doesn't appear. Instead of exit you should probably catch the close event instead.
There's also an issue of implicit conversion to string in your code (pdf += data), which could cause problems as well.
I think this will work:
var chunks = [];
child.stdout.on('data', function(data) {
  // insert error check here...
  chunks.push(data);
});
child.on('close', function() {
  var pdf = Buffer.concat(chunks);
  res.send(pdf);
});