'Reading node child process (spawn) stdout with line breaks
I'm trying to run a child process in node.js with
function runProcess (args) {
args = args || [];
var proc = spawn('node', [path.join(__dirname, '..', 'bin', 'library.js')].concat(args), {cwd: __dirname});
proc.stdout.setEncoding('utf8');
return proc;
}
I have a test in which I use the function above:
describe('test', function () {
it('should list installed generators', function (done) {
var process = runProcess();
var data = '';
process.stdout.on('data', function(data) {
var str = data.toString(), lines = str.split(/(\r?\n)/g);
for (var i=0; i<lines.length; i++) {
console.log("chucnk ---------> " + lines[i]); // only prints one line
}
});
process.on('close', function (code) {
code.should.equal(0);
data.should.match(/\[process\] ├── bad/);
data.should.match(/\[process\] └── test/);
done();
});
});
The process is using chalk and a file called log.js to display the console output:
var chalk = require('chalk');
module.exports = function(){
'use strict';
var sig = '['+chalk.green('process')+']';
var args = Array.prototype.slice.call(arguments);
args.unshift(sig);
console.log.apply(console, args); // Invoked 3 times!
return this;
};
If I run the process manually I can see the expected output:
[process] Installed generators
[process] ├── bad
[process] └── test
but when I run it on the unit test the lines 2 and 3 are missing
chucnk ---------> [process] Installed generators
chucnk --------->
chucnk --------->
I tried the proposed at NodeJS spawn stdout string format with no luck.
Do you know why I can't read the lines after the first one?
Solution 1:[1]
This worked for me:
child.stdout.on('data', (data) => {
process.stdout.write(data);
});
but I think you said you tried this already
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Richard Oliver Bray |