How to spawn child processes in Node.js

· Category: Node.js

Short answer

Use child_process.spawn() for long-running processes with streaming output, and child_process.exec() for short commands that return small output buffers.

Steps

  1. Import the module: const { spawn, exec } = require('child_process');.
  2. Spawn a process: const ls = spawn('ls', ['-la']);.
  3. Listen to stdout: ls.stdout.on('data', data => console.log(data.toString()));.
  4. Use exec for simple commands: exec('node -v', (err, stdout) => { ... });.
  5. Always handle the error and close events.

Tips

  • spawn is more efficient for large outputs because it streams data. exec buffers the entire output and has a default max buffer limit.
  • Use execFile when you do not need a shell and want slightly better performance.

Common issues

  • Command injection is possible if you pass unsanitized user input to exec or spawn with shell: true.
  • The working directory of the child process defaults to the parent process; set cwd explicitly if needed.