Nodejs child_proccess.spawn no output using stdio: 'inherit'

Viewed 50

I'm using node.js child_proccess.spawn() in order to execute few command lines in CMD and get the output. I have encountered few issues:

  1. When i'm trying to spawn the proccess witout stdio: 'inherit' option - The CMD freezes after executing the last command and won't print out the results.
  2. When I add the stdio: 'inherit' option, I get the results printed to my terminal but I cant catch the output with child.stdout.on.. Is there any possible way to capture the terminal output or to avoid the proccess from being stuck?
      function executeCommands (){
      
        const firstCommand = 'do something1'
        const secondCommand = 'do something2'
        const thirdCommand = 'do something3'
        let child = require('child_process').spawn(`${firstCommand} && ${secondCommand} && 
        ${thirdCommand}`, [], {shell: true,stdio: 'inherit'})
        
         child.stdout.setEncoding('utf8')
         child.stdout.on('data', (data) => {
         console.log('stdout',data)
         })

         child.stdio.on('data', (data) => {
         console.log('stdio',data)
         })
    
         child.stderr.on('data', (data) => {
         console.log('stderr',data.toString())
         })

    }
1 Answers

Use child_process

const { execSync } = require("node:child_process");

const npmVersion = execSync("npm -v", { encoding: "utf-8" });

console.log(npmVersion);

// 8.15.0

if you want to use spawnSync

const { spawnSync } = require("node:child_process");

const npmVersion = spawnSync("npm", ["-v"], { encoding: "utf-8" });

console.log(npmVersion.stdout);

// 8.15.0

Related