Node.js › Child Processes & Process Management

How do you handle a child process that hangs or never terminates, and what's the correct way to enforce a timeout?

Advanced

Answer

Both exec() and execFile() support a 'timeout' option that automatically sends a kill signal to the child process if it hasn't completed within the specified duration; for spawn(), which doesn't have a built-in timeout option, you implement this manually with setTimeout() calling child.kill() if the process hasn't emitted its 'exit' event within the allowed time, typically also clearing that timeout if the process finishes normally first.
const { spawn } = require('node:child_process');

const child = spawn('some-long-command');
const timeout = setTimeout(() => {
  child.kill('SIGTERM');
  console.error('Process timed out and was killed');
}, 30000);

child.on('exit', () => clearTimeout(timeout));
Real-world example A code-execution service running user-submitted scripts as child processes enforces a strict 10-second timeout, forcibly killing any script that runs longer, preventing a single infinite-looping or malicious submission from tying up a worker slot indefinitely.

Common follow-ups: What's the difference between SIGTERM and SIGKILL when force-terminating a hung process, and when would you need to escalate from one to the other?;How do you ensure any resources (file handles, network connections) held by the killed child are properly cleaned up?