Node.js, Pipes, and Disappearing Bytes
sxlijin.github.io
sxlijin.github.io
function flushWritableStream(stream: NodeJS.WritableStream) {
return new Promise(resolve => stream.write("", resolve)).catch(
handleFlushError,
)
}
/**
* In NodeJS, process.stdout and process.stderr behave inconsistently depending on the type
* of file they are connected to.
*
* When connected to unix pipes, these streams are *async*, so we need to wait for them to be flushed
* before we exit, otherwise we get truncated results when using a Unix pipe.
*
* @see https://nodejs.org/api/process.html#process_a_note_on_process_i_o
*/
export async function flushStdoutAndStderr() {
await Promise.all([
flushWritableStream(process.stdout),
flushWritableStream(process.stderr),
])
}
/**
* If `module` is the NodeJS entrypoint:
*
* Wait for `main` to finish, then exit 0.
* Note that this does not wait for the event loop to drain;
* it is suited to commands that run to completion.
*
* For processes that must outlive `main`, see `startIfMain`.
*/
if (require.main === module) {
await main(argv)
await flushStdoutAndStderr()
setTimeout(() => process.exit(0))
} $ node -e "process.stdout.write('@'.repeat(128 * 1024)); process.stdout.write(''); process.exit(0);" | wc -c
65536
You want to use `Stream.finished`: $ node -e "const { Stream } = require('stream'); s = process.stdout; s.write('@'.repeat(128 * 1024)); Stream.finished(s, () => { process.exit(0); })" | wc -c
131072
https://nodejs.org/api/stream.html#streamfinishedstream-opti...If this helps you, consider bothering your infra team to look at opening access back up for tor IPs (;
That's missing the part where it waits for the last write to flush before exiting.
$ node -e "process.stdout.write('@'.repeat(128 * 1024)); process.stdout.write(''); setTimeout(()=>{ process.exit(0); }, 0);" | wc -c
131072
Sure. But not so fast! You're still just racing and have no guarantees. Increase the pressure and it snaps back: $ node -e "process.stdout.write('@'.repeat(1280 * 1024)); process.stdout.write(''); setTimeout(()=>{ process.exit(0); }, 0);" | wc -c
65536
Meanwhile: $ node -e "const { Stream } = require('stream'); s = process.stdout; s.write('@'.repeat(1280 * 1024)); Stream.finished(s, () => { process.exit(0); })" | wc -c
1310720Once we await that callback to resolve, then the buffered data from before that point is known to be flushed. I don’t want to wait for a “finished” event because I want my program to terminate once my main() function and a flush after main() is complete. If I wait for finish, a background “thread” can extend the process lifetime by continuing to log.
This is also why we don’t set process.exitCode and wait for the event loop to drain and Node to auto-exit. That might be the “right way”, but if someone leaves a lingering setTimeout(…, 10_MINUTES) you’ll have a bad time.
It’s also more clear to reason about. Our rule: if you want the process to wait for your async work to complete, then `await` it.
This is not true IME. Just more likely.
See my comment here: https://news.ycombinator.com/item?id=41829905
> If I wait for finish, a background “thread” can extend the process lifetime by continuing to log.
Can you not address this by calling .end() on the stream?
https://nodejs.org/api/stream.html#writableendchunk-encoding...
> Our rule: if you want the process to wait for your async work to complete, then `await` it.
In general I very much agree. In this specific case, though, the awaits are just buying you a bit more time to race the buffer which is why they appear to help. The "flush" will not wait for completion before exiting the process.
Maybe also worth keeping in mind that even if this would be working, stuff like this has historically changed breakingly a few times between major Node releases. If you're relying on unspecified behavior you're obviously in darker waters.
Your comment isn't equivalent to the original code.
Your one liner is doing this: `process.stdout.write('')`
Jitl's example is doing this: `new Promise(resolve => stream.write("", resolve))`
He's passing in a promise resolver as the callback to stream.write (this is basically a `util.promisify` version of the writable.write chunk callback). If the data is written in order (which it should be), then I don't see how the `stream.write` promise could resolve before prior data is flushed. The documentation says: "The writable.write() method writes some data to the stream, and calls the supplied callback once the data has been fully handled". [1]
[1] https://nodejs.org/api/stream.html#writablewritechunk-encodi...
100%.
Case-in-point: After coming back I realize that indeed I did overlook the callback/promise making the difference for the write call. Sorry for spreading lies!
node -e "process.stdout.write('@'.repeat(128 * 1024)); process.stdout.write('',()=>process.exit(0)); " | wc -c
It writes an empty string and use its callback to detect if it has been flushed, which means previous writes are also flushed.I thought gpt-4o and o1-preview would be able to do this pretty easily, but surprisingly not.
You're surprised that AI doesn't work? I'm not.
Consider yourself blessed, as it is the worst designed code ecosystem I've had stinking up the infrastructure. It is worse than VB in many ways.
"You're surprised that AI doesn't work? I'm not."
In general, most productivity studies quietly hide the fact ML LLM make zero impact on experienced developers performance. However, if the algorithm is well formed arbitrary nonsense, then an LLM can generate plausible sounding slop all day long.
Best of luck =3
Is there a reason it doesn’t use standard nodejs promise semantics (await process.stdout.write)? So probably best solution is util.promisify()?
The key takeaway is the behavior difference between synchronous (files/TTYs) and asynchronous (pipes) writes in Node.js. This explains why `process.exit()` can lead to truncated output when piping.
For those facing similar issues, remember to handle the `drain` event or use a more robust streaming approach to ensure all data is written before exiting. This post is a valuable resource for debugging similar "mysterious" pipe behavior in Node.js applications.
Wait, so what's the solution?
See also `process.on('exit', ...)`; you can conditionally set process.exitCode in it (only if there was no other failure) if you want.
$ node -e "const { Stream } = require('stream'); s = process.stdout; s.write('@'.repeat(128 * 1024)); Stream.finished(s, () => { process.exit(0); })" | wc -c
131072
https://nodejs.org/api/stream.html#streamfinishedstream-opti... $ node -e "fs.writeFileSync(1, Buffer.from('@'.repeat(128 * 1024))); process.exit(0);" | wc -c
131072(If blocking the process on writing synchronously to stdout is indeed what you actually want...)
EINVAL fd is bound to a special file (e.g., a pipe, FIFO, or
socket) which does not support synchronization.
Or as POSIX puts it, [EINVAL]
The fildes argument does not refer to a file on which this operation is possible....is a bit brutal but works. Draining the stream before exiting also kind of works but there are cases where drain will just permanently block.
async function drain(stream) { return new Promise((resolve) => stream.on('drain', resolve)) }
This program will run forever, since we never write to stdout, stdout never "drains":
setInterval(() => console.error("stderr: ", new Date().toISOString()), 5_000)
process.stdout.once("drain", () => {
console.error("stderr: stdout.once.drain, exit")
process.exit(0)
})this title is simply a poetic description of the initial bug report.