← Back to Node.js, page 2

nodejs-0034 · Medium mid

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

spawn starts a command and streams its output. exec runs a command in a shell and buffers all output in a callback. execFile runs a file directly without a shell, which is safer. fork starts a new Node process with a built-in message channel for communication.

Full answer

All four start another process. They differ in how output comes back and in how the command is run.

  • spawn(command, args): starts the process and gives you streams for stdin, stdout and stderr right away. No shell by default. Best for large or long-running output (video conversion, log tailing).
  • exec(commandString): runs the string in a shell (/bin/sh or cmd.exe). Collects stdout and stderr into strings and passes them to a callback when the process ends. There is a maxBuffer limit (1 MB by default), and a larger output makes it fail. Shell features such as pipes and wildcards work. Risk: building the string from user input allows command injection.
  • execFile(file, args): like exec but without a shell, and arguments are passed as an array, so there is no injection through the argument string. Output is buffered.
  • fork(modulePath, args): a special spawn for Node scripts. It adds an IPC channel: child.send(message) and process.on('message') work, and messages are structured data.

Choosing: streaming output uses spawn. A short command with small output and no shell features uses execFile. A shell pipeline written by you (not by users) uses exec. Splitting a Node program across processes uses fork, or worker_threads for lighter weight.

Handle the 'error' event (the command could not start) and the 'exit' or 'close' event (the exit code). A non-zero code is not an error event.

javascript
const { spawn, exec, execFile, fork } = require('node:child_process');
const { promisify } = require('node:util');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

const run = promisify(execFile);
const node = process.execPath;

async function main() {
  // spawn: stream the output
  await new Promise((resolve) => {
    const child = spawn(node, ['-e', "console.log('line 1'); console.log('line 2')"]);
    let output = '';
    child.stdout.on('data', (chunk) => { output += chunk; }); // chunks can split anywhere
    child.on('close', (code) => {
      console.log('spawn output lines:', output.trim().split('\n'));
      console.log('spawn exit code:', code);
      resolve();
    });
  });

  // execFile: no shell, arguments as an array, buffered output
  const { stdout } = await run(node, ['-p', '6 * 7']);
  console.log('execFile result:', stdout.trim());

  // exec: a shell string. Use only with trusted text.
  const viaShell = await promisify(exec)(`"${node}" -p "'sh' + 'ell'"`);
  console.log('exec result:', viaShell.stdout.trim());

  // fork: Node child with a message channel
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'fork-'));
  const childFile = path.join(dir, 'child.js');
  fs.writeFileSync(childFile, "process.on('message', (m) => { process.send({ doubled: m.value * 2 }); process.exit(0); });");
  await new Promise((resolve) => {
    const child = fork(childFile);
    child.on('message', (reply) => console.log('fork reply:', reply));
    child.on('exit', resolve);
    child.send({ value: 21 });
  });
  fs.rmSync(dir, { recursive: true });
}

main();

Each call runs a second Node process, so the example works on any system that has node. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): spawn output lines: [ 'line 1', 'line 2' ] spawn exit code: 0 execFile result: 42 exec result: shell fork reply: { doubled: 42 }

Key points

  • spawn streams, exec and execFile buffer.
  • exec uses a shell, execFile and spawn do not by default.
  • fork adds an IPC message channel for Node scripts.
  • Never build shell strings from user input.

Common mistakes

  • Using exec with a string that contains user input.
  • Running a command that prints a lot with exec and hitting maxBuffer.
  • Treating a non-zero exit code as an 'error' event.
  • Forgetting to kill child processes when the parent exits.

Follow-ups

  • How would you stop a child that runs too long?
  • What is the difference between 'exit' and 'close' events?
  • When is fork better than worker_threads?

Tips

  • Use a table in your head: stream or buffer, shell or no shell, IPC or not.
  • Say 'command injection' when exec comes up.
  • Add that fork processes are heavier than worker threads because each has its own V8.