Node.js
Writable stream
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.
Exercise 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".
Show example 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"));
Test yourself
-
Complete the write method
new Writable({ write(chunk, enc, cb) { console.log("Yazıldı: " + chunk.toString()); ____(); } });
Show answer
new Writable({ write(chunk, enc, cb) { console.log("Yazıldı: " + chunk.toString()); cb(); } });
-
Match each concept to its role
- write(chunk)
- Writes a chunk
- end()
- Ends writing
- "finish"
- Writing is complete
- callback()
- Chunk processed signal
-
What does w.end() do?
w.write("a"); w.end();
- Ends writing and triggers the finish event
- Writes a new chunk
- Deletes the Writable
- Pauses writing but doesn't end it
Show answer
Ends writing and triggers the finish event — end() finishes writing and triggers finish.
Next lesson: pipe