Saturday, 8 January 2022

Run bash in node js

I need to start the bash terminal, sequentially execute several commands, collect their results and quit. What is the correct way to do this in nodejs?

I tried to achieve this with child_process.spawn but it doesn't work as I have expected even with a single command.

Here is the simplified code:

const process = spawn(`bash`, [])

// wait for the process to spawn
await new Promise<void>(resolve => process.once(`spawn`, resolve))

// log any output (expected to be the current node version)
process.stdout.on(`data`, data => console.log(data))

// wait for "node --version" to execute
await new Promise<void>(resolve => process.stdin.write(`node --version\n`, `utf8`, () => resolve()))

// wait for the process to end
await new Promise<void>(resolve => process.once(`close`, resolve))

The problem here is that I do not receive any outputs in stdout while await process.once('spawn') works fine.

I have logged stderr and every other event like process.on and stdout.on('error') but they are all empty. So I'm wondering what is the problem here.

In addition, google has tons of examples on how to run a single command. But I need to run several in the same terminal, wait between each call and collect individual results from stdout. I'm not sure how to do this if this doesn't work as expected with the single command.



from Run bash in node js

No comments:

Post a Comment