Writable streams let you send data piece by piece to a destination like a file or network. This helps handle large data smoothly without waiting for everything at once.
0
0
Writing data with Writable streams in Node.js
Introduction
Saving user input to a file as they type
Sending data over the internet in chunks
Logging information continuously to a file
Processing large data sets without loading all in memory
Syntax
Node.js
const { Writable } = require('node:stream');
const writable = new Writable({
_write(chunk, encoding, callback) {
// process the chunk
callback();
}
});
writable.write(data);The write method sends data to the stream.
The _write function inside the constructor handles each chunk of data.
Examples
This example prints each chunk of data to the console as it is written.
Node.js
const { Writable } = require('node:stream');
const writable = new Writable({
_write(chunk, encoding, callback) {
console.log(chunk.toString());
callback();
}
});
writable.write('Hello');
writable.write(' World!');This example writes data directly to a file named
output.txt.Node.js
const fs = require('node:fs'); const writable = fs.createWriteStream('output.txt'); writable.write('Saving this text to a file.'); writable.end();
Sample Program
This program creates a custom writable stream called Logger that prints each chunk with a prefix. It writes two messages and then ends the stream.
Node.js
const { Writable } = require('node:stream');
class Logger extends Writable {
constructor() {
super();
}
_write(chunk, encoding, callback) {
console.log(`Logging: ${chunk.toString()}`);
callback();
}
}
const logger = new Logger();
logger.write('First message');
logger.write('Second message');
logger.end();OutputSuccess
Important Notes
Always call callback() inside the _write method to signal completion.
Use stream.end() to close the writable stream properly.
Writable streams help manage memory by processing data in chunks.
Summary
Writable streams let you send data piece by piece to a destination.
Implement the _write method to handle each chunk.
Remember to call callback() and end the stream with end().