Child Process in Node.js

From the Node.js Core Modules cheat sheet · Process & OS · verified Jul 2026

Child Process

Execute system commands and spawn new processes

javascript
const { spawn, exec, execSync } = require('child_process')

// Execute simple command (callback-based)
exec('ls -la', (error, stdout, stderr) => {
  if (error) console.error(\`Error: \${error}\`)
  console.log(stdout)
})

// Synchronous execution (blocks)
const result = execSync('npm list', { encoding: 'utf-8' })
console.log(result)

// Spawn for streaming/long-running
const ls = spawn('ls', ['-la', '/usr'])
ls.stdout.on('data', (data) => {
  console.log(\`Output: \${data}\`)
})
💡 exec for simple commands, spawn for complex/streaming
⚠️ Sanitize user input to prevent command injection
📌 fork() is specifically for Node.js scripts
⚡ Use worker_threads for CPU-intensive tasks instead
🔗 Related: execa for better child process handling
processsystem

More Node.js tasks

Back to the full Node.js Core Modules cheat sheet