Faced with the need to run an external process from a nodovskogo script. Let's say the external process is started by the command

yarn install 

In the child_process node module, child_process is a non-blocking exec method, with the help of a callback of which I can see errors

 exec('yarn install', function (error, stdout, stderr) { if (error) console.log(error.code) }) 

However, I need the operation to be performed synchronously, for which I use execSync ,

 execSync('yarn install') 

which no longer output any messages to the console.

How to get the output stream?

  • And which of the output streams do you want to receive: stdout or stderr? - Dmitriy Simushev

1 answer 1

The execSync function allows execSync to specify arbitrary stdin , stdout , stderr streams using the stdio parameter.

For example, if you want to redirect the contents of the stdout process to the stdout parent process, you can use the following code:

 var execSync = require('child_process').execSync; execSync('ls -l ~', {stdio: ['ignore', process.stdout, 'ignore']}); 

More information about the parameter stdio can be read in the official documentation .

  • And besides, execSync returns a buffer with the contents of the stdout executed process. - Yaant
  • @Yaant, right. But the buffer will be available only at the end of the execution of the child process, and the custom stdout will be filled immediately upon receiving the data. - Dmitriy Simushev
  • fine! thank. and if we use the third argument child.stderr , will it be an error message from execSync itself? and is it possible to redirect the stream to a file? - while1pass
  • Yes, the third argument is stderr. And yes, it can be redirected to a file. How to create a stream of writing to a file is written in the documentation for fs.createWriteStream - Dmitriy Simushev
  • @DmitriySimushev, well, it was just an addition to complete the picture. :) So it's clear that using stdio gives you more flexibility. - Yaant