0
0
NodejsHow-ToBeginner · 4 min read

How to Write Using Stream in Node.js: Simple Guide

In Node.js, you write data using streams by creating a writable stream with fs.createWriteStream() or other stream APIs, then use the write() method to send data and end() to finish. Streams handle data efficiently by processing it in chunks instead of loading everything into memory at once.
📐

Syntax

To write data using streams in Node.js, you typically create a writable stream and then use its methods:

  • write(chunk): Sends a chunk of data to the stream.
  • end([chunk]): Signals that no more data will be written and optionally writes a final chunk.

Example syntax:

javascript
const fs = require('fs');
const writableStream = fs.createWriteStream('output.txt');
writableStream.write('Hello, ');
writableStream.write('world!');
writableStream.end();
💻

Example

This example shows how to write text data to a file using a writable stream. It writes two chunks and then closes the stream.

javascript
const fs = require('fs');

const writableStream = fs.createWriteStream('example.txt');

writableStream.write('This is the first line.\n');
writableStream.write('This is the second line.\n');

writableStream.end(() => {
  console.log('Finished writing to example.txt');
});
Output
Finished writing to example.txt
⚠️

Common Pitfalls

Common mistakes when writing with streams include:

  • Not calling end(), which leaves the stream open and data unwritten.
  • Writing data after calling end(), which causes errors.
  • Ignoring the error event, which can crash your program if something goes wrong.

Always listen for error and finish events to handle stream lifecycle properly.

javascript
const fs = require('fs');

const writableStream = fs.createWriteStream('wrong.txt');

// Wrong: writing after end
writableStream.end('Goodbye!');
try {
  writableStream.write('This will cause an error');
} catch (err) {
  console.error('Error:', err.message);
}

// Right way
const correctStream = fs.createWriteStream('right.txt');
correctStream.on('error', (err) => console.error('Stream error:', err));
correctStream.write('Hello!');
correctStream.end('Bye!');
Output
Error: write after end
📊

Quick Reference

Method/EventDescription
write(chunk)Writes a chunk of data to the stream.
end([chunk])Ends the stream, optionally writing a final chunk.
on('finish', callback)Called when all data is flushed and stream is closed.
on('error', callback)Called if an error occurs during writing.

Key Takeaways

Use write() to send data chunks and end() to close the writable stream.
Always handle error events to avoid crashes during stream operations.
Do not write data after calling end() as it causes errors.
Writable streams process data efficiently by handling chunks instead of loading all data at once.
Listening to finish event helps confirm when writing is complete.