They differ in two ways: whether they use a shell, and whether output comes as a stream or all at once (buffered).
spawn(cmd, args) starts a process without a shell. It gives you the process's stdin, stdout and stderr as streams. It suits long-running processes and large output.
exec(command, callback) runs the command string inside a shell. It collects (buffers) all output and passes stdout and stderr to the callback at the end. It is handy for short commands that use pipes or globs (patterns like *.js). It has two risks:
- If the output is larger than
maxBuffer, Node kills the process. - If you put user input into the command string, an attacker can inject extra shell commands. This is shell injection.
execFile(file, args, callback) buffers output like exec. But it runs the program directly, without a shell. So no shell reads or changes the arguments.
fork(modulePath) is a spawn of a new Node process with an IPC channel (inter-process communication: a way to send messages). The parent and child send messages with send and receive them with the message event.
With untrusted input, prefer spawn or execFile and pass the arguments as an array.
spawnuses no shell and streams output, so it suits long-running work.execuses a shell and buffers output, has amaxBufferlimit and risks shell injection.execFilebuffers output likeexecbut runs without a shell.forkstarts a new Node process with an IPC channel for messages.