What is the stream module writable.end() method in Node.js?

The writable.end() method is one of the applications of the stream module interface in Node.js. This method closes the writable stream and prevents any more data from being written to the writable stream.

Syntax

writable.end( chunk, encoding, callback)

Parameters and return value

There are a total of three parameters:

  1. chunk: This is an optional parameter. It specifies one last line of data to write to the stream before closing it.

  2. encoding: The encoding to be used given that chunk is a string value, e.g., utf-8.

  3. callback: This is an optional parameter and the function that is called before executing the end() operation.

When the end() method is called, the code executes its relevant operations for closing the writable stream. Any further writing to the stream will raise an error.

Code

Let’s have a look at the code to understand it better.

Example: normal execution

// stream module
const stream = require('stream');
// creating writable object
const writable = new stream.Writable({
// declaring the write function
write: function(chunk, encoding, next) {
// printing the chunk of data.
console.log(chunk.toString());
next();
}
});
// Writing data
writable.write('hi');
writable.write('hey');
writable.write('hello');
writable.write('how are you?');
// calling end
writable.end("Finishing stream", "utf8", () => {
console.log("Goodbye, Thank you!");
});

Example: error

// stream module
const stream = require('stream');
// creating writable object
const writable = new stream.Writable({
// declaring the write function
write: function(chunk, encoding, next) {
// printing the chunk of data.
console.log(chunk.toString());
next();
}
});
// Writing data
writable.write('hi');
writable.write('hey');
writable.end("Finishing stream", "utf8", () => {
console.log("Goodbye, Thank you!");
});
//writing data after ending the stream. This will raise an error
writable.write("trying to write data after end");

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved