Node.js Stream module
Stream is an abstract interface in Node.js for handling streaming data. You can think of a stream as a flow of water, with data flowing from one place to another just like water. This approach is especially suitable for large files or continuous data sources, because it does not need to load all the data into memory at once.
Why do we need Stream?
- Memory efficiency: when handling large files, you do not need to load the whole file into memory at once
- Time efficiency: data can be processed as it arrives, without waiting for all data to be ready
- Composability: multiple streams can be connected like pipes to form a data-processing pipeline
Four basic types of Stream
1. Readable Stream
A readable stream is a source of data from which you can read. For example, reading content from a file or getting data from an HTTP request.
Example
const
fs
=
require
(
'fs'
)
;
const
readableStream
=
fs.
createReadStream
(
'example.txt'
)
;
readableStream.
on
(
'data'
,
(
chunk
)
=>
{
console.
log
(
`Received $
{
chunk.
length
}
bytes of data`
)
;
}
)
;
readableStream.
on
(
'end'
,
(
)
=>
{
console.
log
(
'No more data'
)
;
}
)
;
2. Writable Stream
A writable stream is a destination for data to which you can write. For example, writing to a file or sending an HTTP response.
Example
const
fs
=
require
(
'fs'
)
;
const
writableStream
=
fs.
createWriteStream
(
'output.txt'
)
;
writableStream.
write
(
'First line of data\n'
)
;
writableStream.
write
(
'Second line of data\n'
)
;
writableStream.
end
(
'Last line of data'
)
;
3. Duplex Stream
A duplex stream is both readable and writable, such as a TCP socket.
Example
const
{
Duplex
}
=
require
(
'stream'
)
;
const
myDuplex
=
new
Duplex
(
{
write
(
chunk
,
encoding
,
callback
)
{
console.
log
(
chunk.
toString
(
)
)
;
callback
(
)
;
}
,
read
(
size
)
{
this
.
push
(
'Data read from the duplex stream'
)
;
this
.
push
(
null
)
;
// Indicates the end of data
}
}
)
;
4. Transform Stream
A transform stream is a special kind of duplex stream that can modify or transform data as it is read and written, such as compressing or encrypting data.
Example
const
{
Transform
}
=
require
(
'stream'
)
;
const
upperCaseTr
=
new
Transform
(
{
transform
(
chunk
,
encoding
,
callback
)
{
this
.
push
(
chunk.
toString
(
)
.
toUpperCase
(
)
)
;
callback
(
)
;
}
}
)
;
process.
stdin
.
pipe
(
upperCaseTr
)
.
pipe
(
process.
stdout
)
;
Common Stream methods
The pipe() method
pipe() The pipe() method is one of the most powerful features of Stream; it can connect multiple streams to form a pipeline.
Example
const
fs
=
require
(
'fs'
)
;
// Create a readable stream and a writable stream
const
readStream
=
fs.
createReadStream
(
'input.txt'
)
;
const
writeStream
=
fs.
createWriteStream
(
'output.txt'
)
;
// Use pipe to connect the readable stream and the writable stream
readStream.
pipe
(
writeStream
)
;
writeStream.
on
(
'finish'
,
(
)
=>
{
console.
log
(
'Data write complete'
)
;
}
)
;
Event Listening
Stream is an instance of EventEmitter and can handle various situations by listening for events:
data- Triggered when data is available to readend- Triggered when there is no more data to readerror- Triggered when an error occursfinish- Triggered when all data has been flushed to the underlying system
Practical Application Examples
Example 1: File copy
Example
const
fs
=
require
(
'fs'
)
;
function
copyFile
(
source
,
target
,
cb
)
{
// Create read and write streams
const
rd
=
fs.
createReadStream
(
source
)
;
const
wr
=
fs.
createWriteStream
(
target
)
;
// Handle errors
rd.
on
(
'error'
,
err
=>
cb
(
err
)
)
;
wr.
on
(
'error'
,
err
=>
cb
(
err
)
)
;
// Completion callback
wr.
on
(
'finish'
,
cb
)
;
// Start copying
rd.
pipe
(
wr
)
;
}
// Use
copyFile
(
'source.txt'
,
'target.txt'
,
err
=>
{
if
(
err
)
console.
error
(
err
)
;
else
console.
log
(
'Copy complete'
)
;
}
)
;
Example 2: HTTP server compresses a file
Example
const
fs
=
require
(
'fs'
)
;
const
http
=
require
(
'http'
)
;
const
zlib
=
require
(
'zlib'
)
;
http.
createServer
(
(
req
,
res
)
=>
{
// Create a readable stream
const
readStream
=
fs.
createReadStream
(
'./largeFile.txt'
)
;
// Set response headers
res.
writeHead
(
200
,
{
'Content-Type'
:
'text/plain'
,
'Content-Encoding'
:
'gzip'
}
)
;
// Pipeline: read -> compress -> response
readStream.
pipe
(
zlib.
createGzip
(
)
)
.
pipe
(
res
)
;
}
)
.
listen
(
3000
)
;
Best practices for Stream
- Error handling: always add error-handling listeners to streams
- Memory management: for large files, use streams instead of reading everything at once
- Pipeline chains: use the pipe() method sensibly to combine multiple streams
- Backpressure handling: when writing cannot keep up with reading, handle backpressure appropriately
Error-handling example
Example
const
fs
=
require
(
'fs'
)
;
const
readStream
=
fs.
createReadStream
(
'not-exist-file.txt'
)
;
readStream.
on
(
'error'
,
(
err
)
=>
{
console.
error
(
'An error occurred:'
,
err.
message
)
;
}
)
;
By mastering Node.js's Stream module, you can handle a wide variety of I/O operations efficiently; especially when dealing with large files or real-time data, streams will become a powerful tool for you.
Node.js Built-in Modules