Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS spawn stdout string format

I'm spawning a process in node and tracking the output of the command like this:

proc.stdout.on("data", function (data) {
    console.log(data.toString());
});

It works well, however, the output seems to be splitting the lines:

npm http
 304 https://registry.npmjs.org/underscore

The above is just one line out of the response from an npm install. Typically this is all in one line, it's also adding line breaks before and after the response. Is there a way to get the data output to look like the standard run, i.e. line-by-line?

like image 429
Fluidbyte Avatar asked Nov 28 '13 16:11

Fluidbyte


2 Answers

Streams are buffered and emit data events whenever they please (so to speak), not on strict boundaries like lines of text.

But you can use the readline module to parse the buffers into lines for you:

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

readline.createInterface({
  input     : proc.stdout,
  terminal  : false
}).on('line', function(line) {
  console.log(line);
});
like image 183
robertklep Avatar answered Oct 20 '22 21:10

robertklep


There are 3 solutions which come to mind:

// solution #1
process.stdout.write(data);

// solution #2
console.log(data.toString().replace(/[\n\r]/g, ""));

// solution #3
var child_process = require('child_process');
var readline = require('readline');
var proc = child_process.spawn(...);
readline.createInterface({
  input: proc.stdout,
  terminal: false
}).on('line', function(line) {
  console.log(line);
});
like image 21
tim-montague Avatar answered Oct 20 '22 20:10

tim-montague