Node.js Course
Node.js
/
Advanced

Writable Streams

Definition

An abstraction for a destination to which data is written sequentially. It allows you to write large amounts of data chunk-by-chunk.

Explain Like I'm New

If a Readable Stream is drinking soda through a straw, a Writable Stream is spitting that soda into a bucket. You don't try to spit 50 gallons at once; you spit a little bit at a time. The system safely flushes the bucket to the hard drive in the background.

Real World Example

Writing thousands of log entries to an `access.log` file on a busy server. If you opened and closed the file for every single log, the server would crash. You use a Writable Stream to continuously funnel data safely to the file.

Common Use Cases

  • •Writing large files
  • •Sending HTTP responses (res is a writable stream!)

Terminal Output

bash / terminal
const fs = require('fs'); // We will create a writable stream that outputs to the console for this example // In reality, you'd do: const logger = fs.createWriteStream('./access.log'); const logger = process.stdout; console.log("--- Server Logs ---"); // Writing data chunk by chunk logger.write("User Alice logged in.\n"); logger.write("User Bob updated profile.\n"); logger.write("System backup started.\n"); // In a file stream, calling .end() closes the file safely. // We can't call .end() on process.stdout, or we break the terminal! // logger.end(); console.log("--- End Logs ---");

Interview Questions

basic

  • How do you push data into a Writable stream?

intermediate

  • How do you signal that you are completely finished writing to the stream?

Flash Cards

Question

How to push data?

Click to reveal answer
Answer

By calling `writeStream.write(chunk)`.

Question

How to signal you are finished?

Click to reveal answer
Answer

By calling `writeStream.end()`. This flushes any remaining data and gracefully closes the file/connection.