Child Processes
Child processes
spawn()
spawn(
command: string,
args?: Array<string>,
options?: object
): ChildProcess
Command-only mode
args
is omitted and command
contains the whole shell command. We can even use shell features such as piping between multiple executables, redirecting I/O into files, variables, and wildcards.
options.shell
must be true
because we need an shell to handle the shell features.
Args mode
command
contains only the name of the command and args
contains its arguments.
- If
options.shell
istrue
, many meta-characters inside arguments are interpreted and features such as wildcards and variable names work. - If
options.shell
isfalse
, strings are used verbatim and we never have to escape meta-characters.
Options
.shell: boolean|string
(default:false
)
Should a shell be used to execute the command?- On Windows, this option should almost always be
true
. For example,.bat
and.cmd
files cannot be executed otherwise. - On Unix, only core shell features (e.g. piping, I/O redirection, filename wildcards, and variables) are not available if
.shell
isfalse
. - If
.shell
istrue
, we have to be careful with user input and sanitize it because it’s easy to execute arbitrary code. We also have to escape meta-characters if we want to use them as non-meta-characters. - We can also set
.shell
to the path of a shell executable. Then Node.js uses that executable to execute the command. If we set.shell
totrue
, Node.js uses:- Unix:
'/bin/sh'
- Windows:
process.env.ComSpec
- Unix:
- On Windows, this option should almost always be