Writable Stream in Node.js: What It Is and How It Works
writable stream in Node.js is an object that lets you write data piece by piece to a destination like a file or network. It handles data efficiently by buffering and sending it in chunks instead of all at once.How It Works
Think of a writable stream like a water pipe that you can fill gradually. Instead of pouring all water at once, you add small amounts steadily, and the pipe carries it to the destination. This helps avoid overflow and keeps the flow smooth.
In Node.js, a writable stream receives data chunks and writes them to a target such as a file, a network socket, or another process. It manages buffering internally, so if the destination is busy, it temporarily holds data until it can be sent. This makes writing large amounts of data efficient and prevents your program from freezing.
Example
This example shows how to create a writable stream to write text into a file named output.txt. It writes two lines and then closes the stream.
import { createWriteStream } from 'node:fs'; const writable = createWriteStream('output.txt'); writable.write('Hello, this is line one.\n'); writable.write('And this is line two.\n'); writable.end(); writable.on('finish', () => { console.log('Writing finished.'); });
When to Use
Use writable streams when you need to write large data efficiently without loading it all into memory at once. This is common when saving files, sending data over the network, or processing data in chunks.
For example, if you are saving a big video file uploaded by a user, a writable stream lets you write it piece by piece as it arrives. This keeps your app responsive and avoids crashes from memory overload.
Key Points
- A writable stream writes data chunk by chunk to a destination.
- It buffers data internally to handle slow destinations smoothly.
- Use
write()to send data andend()to close the stream. - Writable streams help manage memory efficiently for large data.