Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท child_process, worker_threads and cluster

Node.js child_process.spawn() method

Reference for child_process.spawn() in Node.js: start a program, stream its stdout and stderr, send stdin, handle exit codes, signals, timeouts and ENOENT errors.

child_process.spawn() starts a program as a new process and returns a ChildProcess object immediately, without waiting for it to finish. The program's standard streams are exposed as Node streams (child.stdin, child.stdout, child.stderr), so output arrives in chunks while the program runs and there is no size limit on it. That makes spawn() the right choice for long-running programs, large output and anything interactive.

By default there is no shell: you pass the program and an array of arguments, and each argument reaches the program exactly as written. This avoids quoting problems and shell injection. The other asynchronous helpers, exec() and execFile(), are built on spawn() and add buffering of the output.

NODE
import { spawn } from 'node:child_process';

const child = spawn(process.execPath, ['-e', 'console.log("hi from a child")']);
child.stdout.on('data', (chunk) => process.stdout.write(chunk));

Try it

Node.js Streaming output and the exit code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js stdin, errors and timeouts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
child_process.spawn(command: string, args?: string[], options?: object): ChildProcess
Name Description
command The program to run. Looked up on PATH unless it contains a path separator.
args Argument strings, passed to the program as-is.
options.cwd Working directory of the child.
options.env Environment variables for the child. Default process.env. Pass an object to replace it completely.
options.stdio 'pipe' (default), 'inherit', 'ignore', or an array per descriptor. See stdio options.
options.shell true or a shell path: run command through a shell. Default false.
options.detached Make the child a process-group leader that can outlive the parent. See Detached processes.
options.timeout Milliseconds after which the child is killed with killSignal.
options.killSignal Signal sent on timeout or abort. Default 'SIGTERM'.
options.signal An AbortSignal that kills the child when aborted.
options.argv0 Override the value the program sees as argv[0].
options.uid, options.gid Run as another user or group (POSIX).
options.windowsHide Hide the console window on Windows.

Returns: a ChildProcess. Events: spawn (the process started), error, exit (the process ended; stdio may still be open), close (ended and all stdio closed; use this to read final output) and message (IPC).

Errors: failure to start (program not found, no permission, bad cwd) is delivered as an error event with a code such as ENOENT or EACCES, not as a thrown exception. Invalid arguments (wrong types) throw synchronously (ERR_INVALID_ARG_TYPE). Without an error listener, a spawn failure becomes an uncaught exception.

Usage notes

  • Wait for close, not exit, when you need all the output: exit can fire before the last stdout chunk has been read.
  • code is null when the process was ended by a signal, and signal is the signal name; check both.
  • Always attach an error listener. A missing executable is a normal runtime condition.
  • Use process.execPath to start another Node.js, instead of the name node, so the child uses the same binary as the parent.
  • With shell: true the command string goes through /bin/sh -c (or cmd.exe on Windows) and the arguments are concatenated, not escaped. Never combine it with user input; see Shell injection.
  • A child that fills a pipe nobody reads blocks. If you do not need its output, set stdio: 'ignore' or call child.stdout.resume().
  • For a promise-style wrapper, events.once(child, 'close') is enough, as in the examples.
  • Use spawn() for large or endless output and execFile() for small output you want buffered (execFile).