-1

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())
         })

    }
Tushar Mistry
  • 373
  • 1
  • 9
Amit
  • 11
  • 4

1 Answers1

0

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

Tushar Mistry
  • 373
  • 1
  • 9
  • Hi, this wont work.. The sub process terminal is not exiting, its setting a debug and I want to get the output in real-time.. Using sync methods will wait for the sub process to end - which is not helpful in my case. – Amit Sep 13 '22 at 06:34