EN
Node.js - read child process stdout to variable
1
points
In this short article, we would like to show how to receive child process output in JavaScript script run under Node JS.
child_script.js
file:
console.log('Child script...');
main_script.js
file:
const { execSync } = require('child_process');
console.log('Main script...');
const result = execSync('node child_script.js');
console.log(result.toString());
Usage example (run in the console):
$ node main_script.js
Main script...
Child script...
Notes:
- pay attention we run node process under node process what is not the best practice but sometimes it is necessary,
- by using
toString()
onresult
variable we wait until all data is recived from child process (node child_script.js
),node child_script.js
can be replaced by any command, e.g.ls -al /