Node.js - read child process stdout to variable

1 points
Created by:

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');

Usage example (run in the console):

$ node main_script.js 
Main script...
Child script...


  • pay attention we run node process under node process what is not the best practice but sometimes it is necessary,
  • by using toString() on result 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 /
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂