Node.js › Child Processes & Process Management
What is the 'detached' option when spawning a child process, and when would you use it?
AdvancedAnswer
By default, a child process is tied to its parent's lifecycle in certain ways depending on the platform -- the { detached: true } option allows the child to continue running independently even after the parent process exits, useful for launching a genuinely independent background process (like starting a separate long-running daemon) that shouldn't be killed just because the process that launched it terminates; combined with child.unref(), the parent can also exit without waiting for the detached child.
const { spawn } = require('node:child_process');
const child = spawn('long-running-daemon', [], {
detached: true,
stdio: 'ignore', // don't keep parent alive waiting on child's stdio either
});
child.unref(); // parent process can now exit independently of the childReal-world example A CLI installer tool spawns a background update-checking process using detached: true and unref(), allowing the installer itself to exit immediately after starting the checker, while the checker continues running independently in the background even after the installer's own process has terminated.