node js child process read stdout

Solutions on MaxInterview for node js child process read stdout by the best coders in the world

showing results for - "node js child process read stdout"
Ariana
27 Feb 2020
1//Prints stdout of childprocess(here: from spawning a python script) 
2// line by line, the rest (like errors) as whole:
3
4const { spawn } = require("child_process");
5const { chunksToLinesAsync, chomp } = require('@rauschma/stringio');
6
7const file = require.resolve('./dummyData.py');
8
9async function main() {
10    const ls = spawn("python" , [file]);
11
12    await echoStdout(ls.stdout); 
13
14    async function echoStdout(readable) {
15        for await (const line of chunksToLinesAsync(readable)) { // (C)
16        console.log('LINE: '+chomp(line))
17        }
18    }
19
20    ls.stdout.on("data", data => {
21        console.log(`stdout: ${data}`);
22    });
23    
24    ls.stderr.on("data", data => {
25        console.log(`stderr: ${data}`);
26    });
27    
28    ls.on('error', (error) => {
29        console.log(`error: ${error.message}`);
30    });
31    
32    ls.on("close", code => {
33        console.log(`child process exited with code ${code}`);
34    }); 
35}
36
37main();