Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 exec 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}`)
});
like image 573
ThomasReggi Avatar asked Jun 27 '16 03:06

ThomasReggi


1 Answers

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.

like image 135
mklement0 Avatar answered Oct 29 '22 19:10

mklement0