Capturing bash output from NodeJS


Is it possible to start and continue to capture output from a certain bash process with node? For example: say I was run tail /some/file, how can I keep listening to every new line printed and act on the output?

Problem courtesy of: Ahmed Nuaman


For completeness, I've added this answer as well.

You can use child_process.spawn to spawn a process and monitor it's output. However, for a command like tail, cat, etc that don't run long or continuously you can just use child_process.exec and it will capture the entire output for stdout and stderr and give it to you all at once.

var cp = require("child_process");

cp.exec("tail /some/file", function (err, stdout, stderr) {
    // If an error occurred, err will contain that error object
    // The output for the command itself is held in stdout and stderr vars
Solution courtesy of: Dominic Barnes


var spawn = require('child_process').spawn,
    tail  = spawn('tail', ['-f', '/tmp/somefile']);

child_process module is well documented

Discussion courtesy of: Andrey Sidorov

This recipe can be found in it's original form on Stack Over Flow.