Reputation: 13
I've been trying to capture the output of a child_process for a while now. The following code example is my current attempt.
Code:
// Spawning a shell
var terminal = require('child_process').spawn(`sh`, [], { stdio: [ 'inherit', 'pipe', 'inherit'] });
console.log("Shell spawned!");
terminal.stdout.on('data', (data) => {
console.log(`Received chunk ${data}`);
});
Output:
Shell spawned!
Expected output:
Shell spawned!
$
When using 'inherit' instead of 'pipe' on the stdout option, I get the expected output. But since I need to capture the output of the process/shell, 'inherit' has no use to me. My question now is, how can I capture the whole output of the process's stdout stream and what is 'inherit' exactly doing? I tried to capture the process.stdout after using 'inherit'- obviously with no luck.
Upvotes: 1
Views: 2279
Reputation: 1521
It is not possible to show the prompt from a child process shell because bash (and I assume other shells) don't output the prompt to stdout. See this post for details.
You can simulate it by writing to standard out instead of console.log().
const term = require('child_process')
.spawn('sh', [], { stdio: [ 'inherit', 'pipe', 'pipe'] });
process.stdout.write('$ ');
term.stdout.on('data', (data) => {
process.stdout.write(`\n${data}$ `);
});
term.stderr.on('data', (data) => {
process.stderr.write(`\n${data}$ `);
});
Upvotes: 0