Why does a Node.js crash handler that logs to stdout and then calls process.exit(1) often lose its final log lines in a container, and what fixes it?
answer
- stdout is not one kind of stream
- pipes behave differently on POSIX
- exit does not wait for pending I/O
- exitCode versus exit()
- write callback or a synchronous write
basics
~20 sOn POSIX, process.stdout writes to a pipe are asynchronous, and process.exit() terminates without waiting for queued writes. Set process.exitCode and let the loop drain, write the fatal line synchronously, or exit from the write callback with a timer as backstop.
solid answer
~40 s`process.stdout` and `process.stderr` behave differently by destination: writes to files are synchronous, to terminals synchronous on POSIX, but to pipes and sockets asynchronous on POSIX, and a container's stdout is usually a pipe to the log collector. `process.exit()` forces the process to exit as quickly as possible even with pending writes to `process.stdout` and `process.stderr`, so whatever the logger queued is dropped. The Node docs recommend setting `process.exitCode` and letting the process exit naturally. In a crash handler where a listening server keeps the loop alive, you instead write the final record synchronously with `fs.writeSync(process.stderr.fd, ...)`, or call `process.exit` from the write callback, with an unref'd timer as a hard backstop. On a laptop terminal the bug hides, because TTY writes are synchronous on POSIX.
code
javascript · 12 lines// fatal.cjs
function fatal(err) {
const line = `${JSON.stringify({ level: 'fatal', msg: err.message, stack: err.stack })}\n`;
setTimeout(() => process.exit(1), 2000).unref(); // backstop if the pipe is stuck
process.stdout.write(line, () => process.exit(1)); // exit once the line is flushed
}
process.on('uncaughtException', fatal);
setTimeout(() => {
throw new Error('payment state corrupted');
}, 10);go deeper
Remember that process.exit() can cut off output that has not been written yet, and that setting process.exitCode is the gentler way to report failure.
Explain the destination table: files synchronous, terminals synchronous on POSIX, pipes asynchronous on POSIX, and why that makes the bug invisible locally.
Choose the right fix for the context: exitCode for scripts, a synchronous write for a crash handler, a write callback with an unref'd backstop, and --trace-exit to find stray exits.
Make a crash record a guaranteed artefact: one shared fatal-logging path, synchronous at the end, and a rule that libraries never call process.exit() themselves.
## What process.exit() abandons `process.exit(code)` tells Node.js to terminate the process **synchronously** with that exit status. Node still calls every `'exit'` listener first, but after that nothing else runs. The docs spell out the cost: calling it forces the process to exit as quickly as possible **even if asynchronous operations are still pending**, including I/O to `process.stdout` and `process.stderr`. A logger that formats a line and hands it to `process.stdout.write()` has not necessarily written anything to the operating system yet. If `process.exit()` runs before that write completes, the line is lost, and with it the one record explaining why the process died. ## Why only production loses the lines The standard streams are not ordinary Node streams. Whether a write is synchronous depends on what the stream is connected to and on the platform: | Destination | Windows | POSIX (Linux, macOS) | |---|---|---| | File | Synchronous | Synchronous | | TTY (terminal) | Asynchronous | Synchronous | | Pipe or socket | Synchronous | **Asynchronous** | On a developer's laptop stdout is a terminal, so on Linux or macOS every `console.log()` completes before the next statement and `process.exit(1)` loses nothing. In a container, under a process supervisor, or behind `| tee`, stdout is a pipe, writes become asynchronous, and the same code drops its last lines. The bug is invisible in local testing by construction. The same table applies to `process.stderr`, so switching the crash line from `console.log()` to `console.error()` does not fix anything by itself. A logging library can add a second layer: many keep their own in-memory buffer and hand it to the stream later, so even a synchronous destination can lose the last records when `process.exit()` runs before the library flushes. Check how the logger you use exposes a final flush before relying on it in a crash path. ## process.exitCode versus process.exit() - **`process.exitCode`** is a value, default `undefined`, that becomes the exit status when the process exits gracefully or through `process.exit()` without an argument. Assigning it never stops anything. - **`process.exit(code)`** ends the process now; a code passed to it beats a previously set `process.exitCode`. - Since Node 20 both accept only an integer, a string that represents an integer, `null` or `undefined`. - The docs add that if a process must die because of an error, throwing an uncaught error and letting it terminate is safer than calling `process.exit()`. ## Fixes, in order of preference 1. **Scripts and command-line tools: set `process.exitCode = 1` and return.** With nothing else scheduled, the loop drains, pending stdout writes complete, and Node exits with that code. This is the pattern the Node docs prescribe. 2. **A crash handler in a server: write the last record synchronously.** `fs.writeSync(process.stderr.fd, line)` hands the bytes to the operating system before it returns, or throws if it cannot, so `process.exit(1)` right after it does not depend on the event loop running again. This is the pattern the Node docs' own `'uncaughtException'` example uses, and blocking the loop is acceptable at this moment because the process is about to die. 3. **A crash handler with an asynchronous logger: exit from the write callback.** `process.stdout.write(line, () => process.exit(1))` exits once the chunk is flushed. Pair it with `setTimeout(() => process.exit(1), 2000).unref()` so a stuck pipe cannot keep a broken process alive. 4. **Find surprise exits.** `--trace-exit` prints a stack trace whenever an environment exits proactively by calling `process.exit()`, which locates the library that calls it behind your back. ## Costs to keep in mind - **Synchronous writes block the event loop.** The docs warn that under load, with slow terminals or with a pipe nobody reads, synchronous writes can stall the process badly, so reserve them for the final crash record rather than everyday logging. - **`process.exitCode` alone does not end a crashed server.** A listening socket keeps the loop alive, so a handler that only assigns the code leaves the process running in an unknown state. - **A backstop timer bounds the wait, not the loss.** If the pipe is truly blocked, the backstop exits without the line; only the synchronous write finishes without waiting for another turn of the event loop.
- How do you find out which code is calling process.exit() in a Node.js service?Start the process with `--trace-exit`, which prints a stack trace whenever the environment is exited proactively through `process.exit()`. The stack points at the dependency or code path that ended the process, which is otherwise invisible because the exit leaves no error behind.
- Does setting process.exitCode = 1 in an 'uncaughtException' handler end a crashed Node.js HTTP server?No. `process.exitCode` only chooses the status for a later exit. The listening server keeps the event loop alive, so the process keeps serving after an exception that left its state unknown. A crash handler must also end the process, after making sure its last log line is written.
- console.log is always synchronous in Node.
- process.exit() waits for stdout to flush before the process ends.
- Setting process.exitCode = 1 terminates the process.
- If the logs survive in my terminal, they will survive in the container.
- process.exit() skips the 'exit' listeners.