title: Parse output of spawned node.js child process line by line
body: <p>I have a PhantomJS/CasperJS script which I'm running from within a node.js script using <code>process.spawn()</code>. Since CasperJS doesn't support <code>require()</code>ing modules, I'm trying to print commands from CasperJS to <code>stdout</code> and then read them in from my node.js script using <code>spawn.stdout.on('data', function(data) {});</code> in order to do things like add objects to redis/mongoose (convoluted, yes, but seems more straightforward than setting up a web service for this...) The CasperJS script executes a series of commands and creates, say, 20 screenshots which need to be added to my database.</p>
  
  <p>However, I can't figure out how to break the <code>data</code> variable (a <code>Buffer</code>?) into lines... I've tried converting it to a string and then doing a replace, I've tried doing <code>spawn.stdout.setEncoding('utf8');</code> but nothing seems to work...</p>
  
  <p>Here is what I have right now</p>
  
  <pre><code>var spawn = require('child_process').spawn;
  
  var bin = "casperjs"
  //googlelinks.js is the example given at http://casperjs.org/#quickstart
  var args = ['scripts/googlelinks.js'];
  var cspr = spawn(bin, args);
  
  //cspr.stdout.setEncoding('utf8');
  cspr.stdout.on('data', function (data) {
      var buff = new Buffer(data);
      console.log("foo: " + buff.toString('utf8'));
  });
  
  cspr.stderr.on('data', function (data) {
      data += '';
      console.log(data.replace("\n", "\nstderr: "));
  });
  
  cspr.on('exit', function (code) {
      console.log('child process exited with code ' + code);
      process.exit(code);
  });
  </code></pre>
  
  <p><a href="https://gist.github.com/2131204">https://gist.github.com/2131204</a></p>