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.
writable.end( chunk, encoding, callback)
There are a total of three parameters:
chunk
: This is an optional parameter. It specifies one last line of data to write to the stream before closing it.
encoding
: The encoding to be used given that chunk
is a string value, e.g., utf-8
.
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.
Let’s have a look at the code to understand it better.
// stream moduleconst stream = require('stream');// creating writable objectconst writable = new stream.Writable({// declaring the write functionwrite: function(chunk, encoding, next) {// printing the chunk of data.console.log(chunk.toString());next();}});// Writing datawritable.write('hi');writable.write('hey');writable.write('hello');writable.write('how are you?');// calling endwritable.end("Finishing stream", "utf8", () => {console.log("Goodbye, Thank you!");});
// stream moduleconst stream = require('stream');// creating writable objectconst writable = new stream.Writable({// declaring the write functionwrite: function(chunk, encoding, next) {// printing the chunk of data.console.log(chunk.toString());next();}});// Writing datawritable.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 errorwritable.write("trying to write data after end");
Free Resources