Fixing EPIPE When Piping Node.js Output to head
When you pipe a Node.js script's output to | head to look at only the first few lines, you may see Error: write EPIPE and the process exits with code 1. The cause is that Node.js keeps writing output after head has read the lines it needs and exited. If you listen for the error event on process.stdout and exit quietly when the error is EPIPE, the error goes away.
The same fix also applies when you pass a command-line tool's output to head, grep -m 1, or similar commands, or when a command in the middle of a pipeline is treated as a failure in a shell script or CI. In my test environment, I caused the error, recorded the full message, and confirmed that the error disappeared after the fix.
The test environment was Ubuntu 24.04 with Node.js 22.23.5 and 24.22.3, and the head from GNU coreutils 9.4. I did not test Windows, macOS, shells other than bash, or EPIPE errors from writing to files or sockets.
The script that causes the error
I wrote write.js, which uses process.stdout.write to write 100,000 lines one at a time.
for (let i = 1; i <= 100000; i++) {
process.stdout.write(`line ${i}\n`);
}
I pass its output to head -n 3.
The full error output
On Node.js 24.22.3, after three lines were displayed, it stopped with the following output (the path is replaced with a placeholder value):
$ node write.js | head -n 3
line 1
line 2
line 3
node:events:505
throw er; // Unhandled 'error' event
^
Error: write EPIPE
at afterWriteDispatched (node:internal/stream_base_commons:138:10)
at writeGeneric (node:internal/stream_base_commons:126:10)
at Socket._writeGeneric (node:net:1324:11)
at Socket._write (node:net:1336:8)
at writeOrBuffer (node:internal/streams/writable:574:12)
at _write (node:internal/streams/writable:503:10)
at Writable.write (node:internal/streams/writable:512:10)
at Object.<anonymous> (/path/to/app/write.js:2:18)
at Module._compile (node:internal/modules/cjs/loader:1929:14)
at Object..js (node:internal/modules/cjs/loader:2060:10)
Emitted 'error' event on Socket instance at:
at emitErrorNT (node:internal/streams/destroy:170:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at process.processTicksAndRejections (node:internal/process/task_queues:90:21) {
errno: -32,
code: 'EPIPE',
syscall: 'write'
}
Node.js v24.22.3
Checking bash's PIPESTATUS, the exit code of node was 1 and the exit code of head was 0. I repeated the same run five times, and each time I got this error.
On Node.js 22.23.5, the shape was the same from Error: write EPIPE through syscall: 'write'. The differences were that the first line is node:events:497, the indentation of the throw er and ^ lines differs, the line and column numbers in the at … lines differ, and the version line at the end differs. I omit the full Node.js 22 output.
Here is how to read the message:
Unhandled 'error' eventmeans that no handler (listener) was set up to receive theerrorevent. As the official documentation on error events explains, if anerrorevent occurs with no listener, the error is thrown and the Node.js process exits.Error: write EPIPEandsyscall: 'write'indicate that the write failed with EPIPE (Broken pipe). The official list of system errors describes EPIPE as the error you get when writing to a pipe or similar that has no process reading from it.at Object.<anonymous> (/path/to/app/write.js:2:18)is the location in your own script where the write happened.Emitted 'error' event on Socket instanceshows that theerrorevent was emitted on a Socket. According to the official documentation for process.stdout,process.stdoutis anet.Socketstream when the output goes to something other than a file.
head -n 3 exits after reading three lines, which leaves no reading end for the pipe. Node.js kept writing after that, which caused the EPIPE.
Different from how yes exits
For comparison, I passed the yes command, which writes y continuously, to head -n 2. yes exited with code 141 and printed no message. In the bash of my test environment, a process terminated by SIGPIPE (signal 13) also exits with code 141. So yes received SIGPIPE when it wrote to a pipe with no reader, and it exited silently.
On the other hand, the official documentation on signal events says that Node.js ignores SIGPIPE by default. As a result, Node.js does not exit from the signal. Instead, the failure arrives as a write error (EPIPE).
Discarding the error message does not fix it
If you discard stderr with 2>/dev/null, the message disappears from the screen. However, the exit code of node stayed at 1.
$ node write.js 2>/dev/null | head -n 3
line 1
line 2
line 3
When I used set -o pipefail in a shell script, the exit code of the whole pipeline was also 1. A shell script or CI job that judges success by exit code treats this 1 as a failure.
$ set -o pipefail; node write.js 2>/dev/null | head -n 3 >/dev/null; echo $?
1
Fixing it by handling the error event
Attach an error event listener to process.stdout, and exit with code 0 when the error is EPIPE. Rethrow any other error as before.
process.stdout.on('error', (err) => {
if (err.code === 'EPIPE') {
process.exit(0);
}
throw err;
});
for (let i = 1; i <= 100000; i++) {
process.stdout.write(`line ${i}\n`);
}
I ran this as fix-handler.js. Only three lines were displayed, and the error no longer appeared. Stderr was empty, and the exit code of node was 0. I ran it six times each on Node.js 22.23.5 and 24.22.3, and got the same result every time.
$ node fix-handler.js | head -n 3
line 1
line 2
line 3
With set -o pipefail enabled, the exit code of the whole pipeline was also 0.
$ set -o pipefail; node fix-handler.js | head -n 3 >/dev/null; echo $?
0
Waiting for drain to stop writing early
The fix above removes the error, but the for loop does not stop. When I added a line count to stderr at exit to check, the script wrote all 100,000 lines every time, even after head finished after three lines. When I also printed the count from inside the listener, the listener was called only after the loop had written all 100,000 lines and exited.
If generating the output is expensive, check the return value of write(). When it is false, wait for the drain event. The official documentation for writable.write() says that when false is returned, writing should pause until the drain event is emitted.
const { once } = require('node:events');
process.stdout.on('error', (err) => {
if (err.code === 'EPIPE') {
process.exit(0);
}
throw err;
});
async function main() {
for (let i = 1; i <= 100000; i++) {
if (!process.stdout.write(`line ${i}\n`)) {
await once(process.stdout, 'drain');
}
}
}
main();
I ran this as fix-drain.js. On both Node.js 22.23.5 and 24.22.3, the display was three lines, stderr was empty, and the exit code was 0. When I added a line counter to test it, the script also stopped after writing 3 to 9 lines (the count changes on each run). The count printed from inside the listener was the same: the listener was called while the script was waiting for drain, and the script ended there.
console.log does not error, but it keeps writing
I changed process.stdout.write to console.log in print.js. Piped to head -n 3 in the same way, it produced no error, and the exit code was 0.
for (let i = 1; i <= 100000; i++) {
console.log(`line ${i}`);
}
The official documentation for the Console class has an option called ignoreErrors that ignores errors from the output destination, and says its default is true when you create a Console with new Console(). The global console not producing an error this time matches that behavior. However, although no error appeared, when I counted the lines written, this case also wrote all 100,000 lines before exiting.
The EPIPE you get when piping to head only signals that the reader has read what it needed and exited first. It does not mean your script's processing failed. So it is fine to exit with code 0 for EPIPE alone. Check err.code and separate it from other errors, so that you do not turn every error into exit code 0.




