Home > Software design >  Display powershell output as a stream in electron-react app
Display powershell output as a stream in electron-react app

Time:12-24

I want to run some powershell commands and stream (that cli command takes some time and prints few line as the process proceeds) its output in react(i use electron and its configured)

i tried this but its not a stream, it just prints all lines altogether. the actualy output will print line by line

const { exec } = require("child_process")
exec("spicetify apply", { shell: "powershell.exe" }, (error, stdout, stderr) => {
    console.log(stdout)
})

CodePudding user response:

  • Don't use exec, because it won't call your event handler with the process' output until after the process has terminated, i.e. it will not stream; use spawn instead.

  • You don't need to involve a shell in order to call an external executable with arguments; you only need to call via a shell if you need shell features such as output redirection (>), which is not the case here. Not calling via a shell speeds up your command, which is especially noticeable with powershell.exe, whose startup cost is nontrivial.

const { spawn } = require("child_process")
let child = spawn("spicetify", [ "apply" ])
child.stdout.on('data', (data) => console.log(data.toString())) 
  • Related