Node.js streams for reading, writing, copying, compression, and two-way communication
🎯 Introduction
By the end of this article, you will be able to read and write file chunks, copy and compress files with pipeline, and exchange data through duplex streams.
🧱 Streams process data a piece at a time
A stream receives or outputs data incrementally. For large files or continuously produced content, a program can process each portion as it arrives rather than loading everything into memory first.
Even asynchronous readFile delivers the entire file after reading finishes. Streams deliver chunks, individual portions of arriving data. A chunk does not necessarily correspond to a line of text or a complete message.
For a small configuration file, readFile is usually simpler. Streams are better suited to controlling data buildup when copying large files or processing continuous network content. They still need buffers for temporary storage and do consume memory.
📖 Readable: read data from a source
A Readable stream supplies data to a program. Use createReadStream to create a file data source.
This article uses Node.js 24.19.0. Prepare a UTF-8 note.txt containing hello, and start read-stream.mjs with:
import { createReadStream } from 'node:fs'
const source = createReadStream('note.txt', { encoding: 'utf8' })
source is a readable stream object, not the file contents. encoding: 'utf8' delivers text as strings. Without an encoding, file streams generally deliver Buffer byte objects.
Append code to consume it:
try {
for await (const chunk of source) {
console.log(chunk)
}
} catch (error) {
console.error('Read failed:', error.code)
}
Run node read-stream.mjs. This small file usually produces a single hello chunk. for await retrieves asynchronously arriving data in sequence and ends when reading finishes. If the file is missing, catch reports ENOENT.
With a text encoding specified, the stream handles character boundaries across chunks, avoiding decoding partial bytes of a Chinese character independently. It does not split text into lines, so a chunk is not necessarily a complete line.
✍️ Writable: write data to a destination
A Writable stream receives data. Use it as a file output destination. Save this separately as write-stream.mjs:
import { createWriteStream } from 'node:fs'
const target = createWriteStream('stream-note.txt', { flags: 'wx' })
target.on('error', error => console.error(error.code))
target.on('finish', () => console.log('Write complete'))
target is a writable object. flags: 'wx' requires creating a new file and reports EEXIST if it already exists, preventing overwrites. The listeners handle failure and completion respectively. Creating the object does not mean writing has finished.
Append:
target.end('hello')
end can submit final content and declare that no more writes will follow. On success, the file contains hello and the finish listener prints Write complete. end returns the stream, not the saved file contents.
🧰 pipeline: connect streams, await completion, and handle failures together
Copying a file continuously passes data from a readable stream into a writable stream. Prepare source.txt containing hello, create copy.mjs, and first create both ends:
import { createReadStream, createWriteStream } from 'node:fs'
import { pipeline } from 'node:stream/promises'
const source = createReadStream('source.txt')
const target = createWriteStream('target.txt', { flags: 'wx' })
This imports the Promise version, so you can await the overall result. Immediately connect the streams and wait:
try {
await pipeline(source, target)
console.log('Copy complete')
} catch (error) {
console.error('Copy failed:', error.code)
process.exitCode = 1
}
Run node copy.mjs. Success prints Copy complete, and target.txt contains hello. The Promise fulfills with undefined: you are waiting for completion, not retrieving the full copied content.
A missing source rejects the Promise with ENOENT. An existing target produces EEXIST because of wx. pipeline destroys the relevant streams as appropriate, and the caller decides how to report failure in one catch.
Existing code may connect streams with source.pipe(target). pipe returns the destination stream, so await cannot wait for copying to finish. It also does not coordinate errors across the entire chain. The copy and compression tasks here use the Promise version of pipeline.
🔄 Duplex: send and receive over one connection
Duplex streams support two-way transfer, such as a client sending data to a server while receiving server data. Node.js network socket objects are ready-made Duplex streams. Use them directly rather than implementing your own Duplex class for everyday networking.
The client below sends hello, while the server sends Welcome. Different messages demonstrate the separate reading and writing roles. The built-in node:net module establishes a local TCP connection, which provides a channel for both sides to keep exchanging bytes.
Prepare a server to accept connections
Save this as server.mjs:
import net from 'node:net'
const server = net.createServer(socket => {
socket.setEncoding('utf8')
socket.on('data', text => console.log('Server received:', text))
socket.on('error', error => console.error(error.message))
socket.end('Welcome')
})
server.on('error', error => console.error(error.message))
server.listen(3000, '127.0.0.1', () => console.log('Waiting for connections'))
Run node server.mjs to print Waiting for connections. 127.0.0.1 refers to the local machine, and 3000 is the listening port. Each connection invokes the callback with its socket.
The socket's readable side receives client data through data events. setEncoding decodes received bytes as UTF-8 text. The writable side uses end to send Welcome and finish sending from this side, while it can still receive data from the other side.
Send and receive through the same client socket
Save this separately as client.mjs:
import net from 'node:net'
const socket = net.createConnection({ host: '127.0.0.1', port: 3000 })
socket.setEncoding('utf8')
socket.on('data', text => console.log('Client received:', text))
socket.on('error', error => console.error(error.message))
socket.on('connect', () => socket.end('hello'))
Keep the server running and execute node client.mjs in another terminal. The connect event signals that the connection is established; end then sends hello and finishes client-side sending.
| Location | Received content |
|---|---|
| Server terminal | Server received: hello |
| Client terminal | Client received: Welcome |
The client writes hello but reads the welcome message sent by the server. This is what independent Duplex sides mean: it does not read back its own writes.
This example sends only a short message. TCP carries a byte stream, and one data event is not guaranteed to correspond to one send. Longer content may arrive in multiple portions. The client exits after both sides finish exchanging data; the server keeps waiting for new connections. Press Ctrl+C to stop it after practice.
Use write for ongoing sending and end only when finished. Each side sends once here, so it directly uses end with content.
🧩 Transform: compress a file as it is read
A Transform stream processes input and produces transformed output, such as compressed file data. It is a Duplex stream, but unlike a network connection's independent sides, its output derives from transforming its input. Create a separate compress.mjs and prepare the file source:
import { createReadStream, createWriteStream } from 'node:fs'
import { pipeline } from 'node:stream/promises'
import { createGzip } from 'node:zlib'
const source = createReadStream('source.txt')
node:zlib is the built-in compression module. createGzip creates a gzip Transform stream that receives raw bytes and outputs compressed bytes:
const gzip = createGzip()
gzip is a Transform stream object. Creating it does not yet produce a compressed file. Next, specify the destination for compressed bytes:
const target = createWriteStream('source.txt.gz', { flags: 'wx' })
Finally, connect all three steps:
try {
await pipeline(source, gzip, target)
console.log('Compression complete')
} catch (error) {
console.error('Compression failed:', error.code)
process.exitCode = 1
}
Success creates source.txt.gz. Decompressing it with a gzip-compatible tool yields hello. The order is read, compress, save. Do not decode compressed bytes as utf8 text first.
⚖️ Backpressure: slow reading when writing cannot keep up
Backpressure makes an upstream producer pause when downstream processing cannot keep up. When copying a large file, data accumulates if reading outpaces writing. pipe and pipeline coordinate both ends so the reader does not supply data without limit.
The earlier copy.mjs already uses pipeline. Replace the source with a larger file without writing separate copying logic. It transfers chunks, whereas readFile followed by writeFile first holds the entire contents in memory.
However, collecting every chunk in an array still accumulates the entire file. Running many copies concurrently also increases total memory use. With pipeline, pass chunks through without collecting all content separately.
🪤 Create fresh streams for each transfer
Ended or failed streams retain their state. Do not reuse them for retries. Recreate both ends or the entire chain, and decide explicitly how to handle the target file.
In these examples, rerunning node copy.mjs after modifying the source or fixing a read error creates fresh streams. If failure left target.txt, confirm it belongs to this exercise and delete it manually before rerunning. Otherwise, wx refuses to write because the target exists.
❓ Questions and answers
Q1: If a small file prints once, is it really using a stream?
Yes. Small contents can arrive in one chunk. Output count does not determine whether streams are used.
Q2: Does creating a writable stream mean saving is finished?
No. Submit data and wait for completion or failure notification.
Q3: Why does copying or compressing again report EEXIST?
The examples use wx to reject overwriting existing files. After confirming the target is your practice output, delete it manually or choose another filename.
Q4: Does pipeline remove the need for catch?
No. pipeline passes chain failures to the caller. catch reports failure and sets the exit code.
🧪 Exercise
Copy and compress a file. Check that the copy and decompressed contents match the source. Then change the read target to a missing file and observe the error code and exit status.
// Write your code here
🎉 Try these techniques with your own examples!
