ThomasReggi ThomasReggi - 7 months ago 29
Node.js Question

Run block of bash / shell in node's spawn

I'm writing a command line utility, and I need stdout to write to TTY or use

{stdio: 'inherit'}
I've been getting by with
but it's not going to cut it. I need way for a spawn process to execute the following echo commands below. I know that spawn spins up a child process with a given command, and you pass in arguments, but I need it to just take a line-separated string of commands like this. This is what I'm currently feeding to exec. Is this possible?

const spawn = require('child_process').spawn
const child = spawn(`
echo "alpha"
echo "beta"

child.stdout.on('data', (data) => {
console.log(`stdout: ${data}`)

child.stderr.on('data', (data) => {
console.log(`stderr: ${data}`)

child.on('close', (code) => {
console.log(`child process exited with code ${code}`)


spawn() does not involve a shell, so in order to have it execute shell commands, you must invoke the shell executable explicitly and pass the shell command(s) as an argument:

const child = spawn('/bin/sh', [ '-c',  `
echo "alpha"
echo "beta"
` ])

Note I've used /bin/sh rather than /bin/bash in an effort to make your command run on a wider array of [Unix-like] platforms.
All major POSIX-like shells accept a command string via the -c option.