Writing to Writable Streams
What You'll Learn
You'll learn how to actively send data to a writable stream using the write() and end() methods.
Sending Data with write()
Now that you can create a writable stream, it's time to push data through it. The write() method is your primary tool for sending chunks of data to the stream:
const fs = require('fs');
const writeStream = fs.createWriteStream('output.txt');
writeStream.write('Hello, ');
writeStream.write('world!\n');
writeStream.write('Another line here.');
Each call to write() sends a chunk to the stream. Think of it like dropping letters into a mailbox one at a time—each piece goes through the system independently.
The write() method returns a boolean: true if the internal buffer can handle more data immediately, false if you should wait. (We'll explore backpressure handling in future lessons.)
Closing the Stream with end()
When you're finished writing, call end() to signal that no more data is coming:
writeStream.end('Final message!\n');
// Stream is now closed, no more writes allowed
You can optionally pass data to end() as a final write-and-close operation. After end() is called, attempting to write more data will throw an error.
The Pattern in Action
const writeStream = fs.createWriteStream('log.txt');
writeStream.write('Starting process...\n');
writeStream.write('Processing data...\n');
writeStream.end('Process complete.\n');
writeStream.on('finish', () => {
console.log('All data written to file');
});
The 'finish' event fires once all data has been flushed to the underlying system—your confirmation that writing is truly complete.
Key Takeaway: Use write() to send data chunks to a writable stream, and always call end() when finished to properly close the stream and ensure all data is flushed.