Run block of bash / shell in node's spawn
Asked Answered
A

1

6

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}`)
});
Aqueduct answered 27/6, 2016 at 3:11 Comment(1)
Does this answer your question? Running a shell command from Node.js without buffering outputFleurette
S
12

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.

Sandbox answered 27/6, 2016 at 3:27 Comment(1)
Perfect, this is exactly what I needed, thanks so much!Aqueduct

© 2022 - 2024 — McMap. All rights reserved.