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
- Import the module:
const { spawn, exec } = require('child_process');. - Spawn a process:
const ls = spawn('ls', ['-la']);. - Listen to stdout:
ls.stdout.on('data', data => console.log(data.toString()));. - Use exec for simple commands:
exec('node -v', (err, stdout) => { ... });. - Always handle the
errorandcloseevents.
Tips
spawnis more efficient for large outputs because it streams data.execbuffers the entire output and has a default max buffer limit.- Use
execFilewhen you do not need a shell and want slightly better performance.
Common issues
- Command injection is possible if you pass unsanitized user input to
execorspawnwithshell: true. - The working directory of the child process defaults to the parent process; set
cwdexplicitly if needed.