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?
AdvancedAnswer
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.