Contents

11/23/2026

Node 'exit' vs 'close': Why Your Script Looks Stuck

Short answer: Node fires a child process's 'exit' event when the process ends, and 'close' only after its stdout and stderr pipes have also closed. If the script you spawned left a background process running that inherited those pipes, 'exit' arrives at once and 'close' waits until that leftover process quits, which can be minutes or never. Fix it at the source by redirecting the background process's output. If you cannot, finish on 'exit' and give the pipes a short, fixed time to drain.

The symptom

A wrapper around a script prints the script's last line, "Done", and then nothing else happens. The job's status stays on "running", the Promise never resolves, and whatever was supposed to run next never runs. The script itself is already gone from the process list.

We hit exactly this on 09/20/2026 in Site Studio, the editor that publishes this site, while it published a post comparing Claude Sonnet's medium and high think settings. The post was live and checked in a fresh browser tab, but the editor still said "publish running...". Its deploy job was waiting for 'close', and a process started during the tar-over-ssh deploy had kept one of the output streams open after the script printed "Done" and exited.

'exit' versus 'close', precisely

The Node.js child_process documentation defines the two events separately, and the difference is the whole bug.

'exit' 'close'
Fires when The child process has ended The child has ended and its stdio streams have closed
Output fully read? Not guaranteed: the docs say stdio streams might still be open Yes, all pipes are closed
Order First Always after 'exit', or after 'error' if the process failed to spawn
Stalls if a leftover process holds a pipe? No Yes, until that process exits or closes the pipe

The docs give the reason for the split: multiple processes can share the same stdio streams. A background process that inherited the child's stdout is one of them.

A reproduction you can run

Two files. deploy.mjs stands in for a deploy script: it starts a helper that sleeps for three seconds with the same stdout, prints "Done", and exits immediately.

// deploy.mjs
import { spawn } from 'node:child_process';

const helper = spawn(
  process.execPath,
  ['-e', 'setTimeout(() => {}, 3000)'],
  { stdio: 'inherit', detached: true },
);
helper.unref();

console.log('Done');

repro.mjs spawns it the usual way and logs both events:

// repro.mjs
import { spawn } from 'node:child_process';

const start = Date.now();
const ms = () => `${Date.now() - start} ms`;

const child = spawn(process.execPath, ['deploy.mjs']);
child.stdout.on('data', (chunk) => console.log(`[${ms()}] stdout: ${chunk.toString().trim()}`));
child.on('exit', (code) => console.log(`[${ms()}] exit  code=${code}`));
child.on('close', (code) => console.log(`[${ms()}] close code=${code}`));

Run with node repro.mjs (Node 24.15.0, Windows 10):

[121 ms] stdout: Done
[140 ms] exit  code=0
[3227 ms] close code=0

The script was done at 140 ms. 'close' came three seconds later, when the helper quit. Make the helper sleep an hour and 'close' comes an hour later.

The fix

1. Cut the pipe where the background process starts

The best fix is in the script that starts the background process: it should not hand over the pipes. We timed four variants, one run each:

Background process started with 'exit' 'close'
Node, stdio: 'inherit' 348 ms 3,500 ms
Node, stdio: 'ignore' 293 ms 293 ms
sh -c 'sleep 3 & echo done' 333 ms 3,350 ms
sh -c 'sleep 3 >/dev/null 2>&1 & echo done' 112 ms 112 ms

The Node documentation's own example for a long-running child uses the same recipe: detached: true, stdio: 'ignore', then unref(). In shell, redirect both streams before the &.

2. If you cannot change the script, finish on 'exit' and let the pipes drain

Sometimes the leftover process is a tool's doing, not yours. The change we shipped in the editor was the minimal one: finish the deploy job on 'exit'. That fixed both symptoms, and it has a regression test. A version that also keeps the output looks like this:

// run.mjs
import { spawn } from 'node:child_process';

export function run(command, args = [], { graceMs = 500 } = {}) {
  return new Promise((resolve, reject) => {
    const child = spawn(command, args);
    let stdout = '';
    let stderr = '';
    child.stdout.setEncoding('utf8').on('data', (chunk) => (stdout += chunk));
    child.stderr.setEncoding('utf8').on('data', (chunk) => (stderr += chunk));

    child.on('error', reject); // spawn failed (for example ENOENT)

    child.on('exit', (code, signal) => {
      let settled = false;
      const finish = () => {
        if (settled) return;
        settled = true;
        clearTimeout(timer);
        // Let go of pipes a leftover process may still hold.
        child.stdout.destroy();
        child.stderr.destroy();
        resolve({ code, signal, stdout, stderr });
      };
      const timer = setTimeout(finish, graceMs);
      child.once('close', finish); // normal case: all output is in, finish now
    });
  });
}

Against deploy.mjs it resolved with "Done\n" about half a second after the exit instead of waiting out the helper. Against a script that wrote 8,000,000 bytes and exited, it returned all 8,000,000, and returned as soon as 'close' fired.

What the grace period costs

Anything the leftover process writes after you stop waiting is lost. We tested a helper that prints "late line" one second after the main script exits:

graceMs stdout returned
200 Done
2500 Done and late line

Pick the number from what you need: if only the main script's output matters, keep it small. The 'error' handler matters too, because the docs say 'exit' may or may not fire after an error, so a handler on one event alone can run twice or not at all.

Timeouts as a backstop

A script that waits on 'close' needs a way out even when the cause is not understood yet. execFile has one, and how it works is worth knowing. With the same deploy.mjs:

Call Callback fired at err
execFile(node, ['deploy.mjs'], cb) 3,530 ms null
execFile(node, ['deploy.mjs'], { timeout: 1000 }, cb) 1,018 ms null

The timeout unstuck it, and it reported success, because the process had exited with code 0 and nothing marked it as killed. The reason is visible in Node's lib/child_process.js: when the timer fires it destroys the child's stdout and stderr before it tries to kill the process, and the callback runs on 'close'.

If you use spawn, build the same thing yourself: a timer that destroys the pipes, like graceMs above. A timeout that only calls child.kill() does nothing for a child that has already exited: in our test kill() returned false and 'close' still arrived at 3,599 ms.

This is the same family of trap as curl exiting 0 on a 404 and a gzip pipe that made a 20-byte backup: a command finishes its own job, and your script needed to know something slightly different. Test the stall once, on purpose, with a helper that outlives its parent.

Aaron Belchamber

Let my Claude help your Claude

If you want a second pair of eyes on how your own setup uses AI-assisted development, that's what this is: me, personally, for AI specifically. Broader business growth and technology consulting is Brandager's own team.

Book a free 30-minute consult

Researched and drafted with AI, then reviewed and edited by the site's editors.

Filed under