Writable stream
- Node.js course
- Intermediate
- Lesson 9/116
- 5 min
Learn to write data with a Writable stream.
Writable stream
A Writable stream flows data from the program to a target. It is created with new Writable({ write(chunk, encoding, callback) { ... } }). The write method is called for each chunk; when done, you call callback().
To write data you use w.write("text"). When all writes are done, call w.end(); this triggers the "finish" event. Example: const w = new Writable({ write(chunk, enc, cb) { console.log("Written: " + chunk.toString()); cb(); } });. Calls w.write("a"); w.write("b"); w.end(); print Written: a, Written: b in order; w.on("finish", ...) catches the completion moment.
Finishing a writable stream
When writing to a Writable, write calls are queued. The end() call means "writing is done"; after it, write is not called. After end(), the "finish" event fires.
Important: inside the write method you must call callback; otherwise the stream stalls. callback() tells Node.js "this chunk is processed, move on". If an error occurs during writing, you pass it with callback(err). This control lets the Writable process chunks safely in order behind the scenes.
Practice Write chunks with a Writable
Create w with new Writable({ write(chunk, enc, cb) { ... } }). Inside write print "Written: " + chunk.toString() and call cb(). Call w.write("line 1") and w.write("line 2"), then w.end(). On the "finish" event print "Done".
Starter code
// Import Writable and create a w instance
// write here
// Write "line 1" and "line 2", then call end()
// write here
// Listen for the "finish" event
// write hereSample solution
const { Writable } = require("stream");
const w = new Writable({
write(chunk, enc, cb) { console.log("Written: " + chunk.toString()); cb(); }
});
w.write("line 1");
w.write("line 2");
w.end();
w.on("finish", () => console.log("Done"));Expected output
Yazıldı: satır 1 Yazıldı: satır 2 Tamam
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the write method
new Writable({ write(chunk, enc, cb) { console.log("Yazıldı: " + chunk.toString()); ____(); } });
new Writable({ write(chunk, enc, cb) { console.log("Yazıldı: " + chunk.toString()); cb(); } });
Explanation: cb() signals the write is done.
2 Match each concept to its role
| Term | Meaning |
|---|---|
write(chunk) |
Writes a chunk |
end() |
Ends writing |
"finish" |
Writing is complete |
callback() |
Chunk processed signal |
3 What does w.end() do?
w.write("a"); w.end();- Ends writing and triggers the finish event Correct answer
- Writes a new chunk
- Deletes the Writable
- Pauses writing but doesn't end it
Explanation: end() finishes writing and triggers finish.