Jorjon
Jorjon

Reputation: 5434

How to read command line output

I want to open a batch file in Nodejs and read its output, while it is printing (not everything at once when the batch finished).

For example, like Jenkins / Hudson.

I'm aware that this will only work on Windows. Any complete example of how to do this will be helpful, as I'm pretty new to Nodejs.

Upvotes: 0

Views: 2007

Answers (1)

dylants
dylants

Reputation: 23340

I believe you'll be fine using Node's child process to run your command and monitor it's output as it prints. This does not have any restrictions on Windows though, so I may be missing something in what you're asking. Let me explain what you could do in hopes that it answers the question.

Imagine you have a file that outputs some text, but does so over time and not all at once. Let's name this file print-something.js. (I realize you've spoken about a batch file, but know that the child_process can execute any executable file. So here I'll be running a JavaScript file via Node, but you could execute a batch file in the same way.)

print-something.js

var maxRuns = 5,
    numRuns = 0;

function printSomething() {
    console.log('some output');
    setTimeout(function() {
        numRuns++;
        if (numRuns < maxRuns) {
            printSomething();
        }
    }, 1000);
}

printSomething();

It's not really important what this file does, but if you study it you'll see it prints "some output" 5 times, but prints each statement with a 1 second gap in-between. Running this from the command line (via node print-something.js) will result in:

some output
some output
some output
some output
some output

So with that we have a file that outputs text in a delayed manner. Turning our attention to the file that reads the output, we have this:

monitor-output.js

var spawn = require('child_process').spawn,
    command = spawn('node', ['print-something.js']);

command.stdout.on('data', function(data) {
    console.log('stdout: ' + data);
});

command.on('close', function (code) {
  console.log('child process exited with code ' + code);
});

This file spawns a process node print-something.js, and then begins to inspect its standard output. Each time it gets data, it prints it to the console. Finally, when the execution has completed, it outputs the exit code. Running node monitor-output.js results in:

stdout: some output

stdout: some output

stdout: some output

stdout: some output

stdout: some output

child process exited with code 0

Most likely you won't be printing the output of this file to the console, but that's what we're doing here just for illustration. Hopefully this gives you an idea on how to monitor output of a file while it runs, and do what you will with it within the child_process.

Upvotes: 1

Related Questions