Jesse Fulton Jesse Fulton - 4 months ago 52
Node.js Question

Parse output of spawned node.js child process line by line

I have a PhantomJS/CasperJS script which I'm running from within a node.js script using

. Since CasperJS doesn't support
ing modules, I'm trying to print commands from CasperJS to
and then read them in from my node.js script using
spawn.stdout.on('data', function(data) {});
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.

However, I can't figure out how to break the
variable (a
?) into lines... I've tried converting it to a string and then doing a replace, I've tried doing
but nothing seems to work...

Here is what I have right now

var spawn = require('child_process').spawn;

var bin = "casperjs"
//googlelinks.js is the example given at
var args = ['scripts/googlelinks.js'];
var cspr = spawn(bin, args);

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);


Try this:

cspr.stdout.on('data', function(data) {
  var str = data.toString(), lines = str.split(/(\r?\n)/g);
  for (var i=0; i<lines.length; i++) {
    // Process the line, noting it might be incomplete.

Note that the "data" event might not necessarily break evenly between lines of output, so a single line might span multiple data events.