Node.js Stream writable.end() Method - GeeksforGeeks

12 Oct, 2021
The writable.end() method is an inbuilt application programming interface of Stream module so that no more data can be written to the Writable anymore. The arguments chunk and encoding are optional which will permit one final new chunk of data to be written instantly before closing the stream. Moreover, the optional callback function is added as a listener for the ‘finish’ event of the Writable stream.
Syntax:
writable.end( chunk, encoding, callback)
Parameters: This method accepts three parameters as mentioned above and described below:
chunk: It is an optional data to write. The value of chunk must be a string, buffer or Uint8Array. For object mode, the chunk value may be anything other than null.
encoding: It holds the encoding value if chunk is a string value.
callback: It is an optional callback function for stream.
Return Value: It returns the data written before calling this method and if the end() method has a chunk of new data then that is also returned at the end.
Below examples illustrate the use of writable.end() method in Node.js:
Example 1:
// Node.js program to demonstrate the     // writable.end() method    // INcluding stream moduleconst stream = require('stream');  // Creating a stream and creating // a write functionconst writable = new stream.Writable({    // Write function with its   // parameters  write: function(chunk, encoding, next) {      // Converting the chunk of    // data to string    console.log(chunk.toString());    next();  }});  // Writing datawritable.write('hi');  // Calling end method with its // all the parameterswritable.end("last data", "utf8", () => {     console.log("Writable stream ended!");});
Output:
hi
last data
Writable {
  _writableState:
   WritableState {
     objectMode: false,
     highWaterMark: 16384,
     finalCalled: false,
     needDrain: false,
     ending: true,
     ended: true,
     finished: false,
     destroyed: false,
     decodeStrings: true,
     defaultEncoding: 'utf8',
     length: 0,
     writing: false,
     corked: 0,
     sync: false,
     bufferProcessing: false,
     onwrite: [Function: bound onwrite],
     writecb: null,
     writelen: 0,
     bufferedRequest: null,
     lastBufferedRequest: null,
     pendingcb: 2,
     prefinished: true,
     errorEmitted: false,
     emitClose: true,
     autoDestroy: false,
     bufferedRequestCount: 0,
     corkedRequestsFree:
      { next: null,
        entry: null,
        finish: [Function: bound onCorkedFinish] } },
  writable: false,
  _write: [Function: write],
  domain: null,
  _events:
   [Object: null prototype] {
     finish: { [Function: bound onceWrapper] listener: [Function] } },
  _eventsCount: 1,
  _maxListeners: undefined }
Writable stream ended!

Example 2:
// Node.js program to demonstrate the     // writable.end() method    // INcluding stream moduleconst stream = require('stream');  // Creating a stream and creating // a write functionconst writable = new stream.Writable({    // Write function with its   // parameters  write: function(chunk, encoding, next) {      // Converting the chunk of    // data to string    console.log(chunk.toString());    next();  }});  // Writing datawritable.write('hi');  // Calling end method with its // all the parameterswritable.end("last data", "utf8", () => {     console.log("Writable stream ended!");});writable.write('GfG');
Output:
hi
last data
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
    at writeAfterEnd (_stream_writable.js:248:12)
    at Writable.write (_stream_writable.js:296:5)
    at /home/runner/LuxuriousLegitimateObservation/index.js:30:10
    at Script.runInContext (vm.js:133:20)
    at Object. (/run_dir/interp.js:156:20)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)Writab
le stream ended!

Here an error is displayed as write() method is called after end() method which is not possible.
Reference: https://nodejs.org/api/stream.html#stream_writable_end_chunk_encoding_callback
Node.js-Stream-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
How to update NPM ?
Node.js fs.writeFile() Method
Difference between promise and async await in Node.js
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript