CodePark/ questions / Workers, cluster & child processes
START PRACTICINGPRACTICE
Backend question · Node.js › Workers, cluster & child processes

What is the difference between spawn, exec, execFile and fork in child_process?

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.

  • spawn uses no shell and streams output, so it suits long-running work.
  • exec uses a shell and buffers output, has a maxBuffer limit and risks shell injection.
  • execFile buffers output like exec but runs without a shell.
  • fork starts a new Node process with an IPC channel for messages.