Howard
Howard

Reputation: 4604

The console output is a mess while executing 'npm install' in child_process.exec

The console output looks good while executing directly in Gitbash as following:

npm info it worked if it ends with ok
npm info using [email protected]
npm info using [email protected]
npm info trying registry request attempt 1 at 12:38:21
npm http GET http://registry.npmjs.org/phonegap
npm http 304 http://registry.npmjs.org/phonegap
npm info installOne [email protected]
...
...

But, if i do the same thing programmatically in nodejs, code snippet as below:

var exec = require('child_process').exec;
var process = exec('npm install -g phonegap', function(err, stdout, stderr){

});

process.stdout.on('data', function(data) {
    console.info(data);
});

process.stderr.on('data', function(data) {
    console.error(data);
});

The console output looks a mess like this:

npm

info

it worked if it ends with
ok
npm info using [email protected]
npm info using
[email protected]

npm

info
 trying
 registry request attempt 1 at 12:44:09
npm http GET http://registry.npmjs.org/phonegap

npm

http
 304 http://registry.npmjs.org/phonegap
...
...

Is there any way to solve this? Thanks

Upvotes: 1

Views: 744

Answers (2)

Robert Levy
Robert Levy

Reputation: 29083

The data event does not correspond to a complete line of text. Use process.stdout.write instead of console.info. This way each write will continue on the same line until you explicitly write a \n.

Upvotes: 0

loganfsmyth
loganfsmyth

Reputation: 161487

console.log and console.error append a newline character after the data they output, and you are calling them for every data event. That means that even if the data event is only part of a line, it gets it's own line.

Instead, you should be writing the data directly to stdout so that it doesn't add random newlines. I'd also not use the name process since that is already the name of a global.

var exec = require('child_process').exec;
var phonegap = exec('npm install -g phonegap', function(err, stdout, stderr){

});
phonegap.stdout.pipe(process.stdout);
phonegap.stderr.pipe(process.stderr);

Upvotes: 2

Related Questions