Node.js | Stream writable.write() Method

The writable.write() method is an inbuilt application programming interface of Stream module which is used to write some data to the Writable stream. The callback function is called once the data has been completely handled.

Syntax:

writable.write( 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 false if the ‘drain’ event is emitted before this method otherwise returns true.

Below examples illustrate the use of writable.write() method in Node.js:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the     
// writable.write() method  
  
// Including stream module
const stream = require('stream');
  
// Creating a stream and creating 
// a write function
const 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();
  }
});
  
// Calling write method with
// all its parameter
writable.write("GfG", "utf8", () => {
     console.log("CS-Portal!");
});

chevron_right


Output:

GfG
true
CS-Portal!

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the     
// writable.write() method  
  
// Including stream module
const stream = require('stream');
  
// Creating a stream and creating 
// a write function
const 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();
  }
});
  
// Calling write method with one
// parameter
writable.write('GeeksforGeeks');

chevron_right


Output:

GeeksforGeeks
true

Reference: https://nodejs.org/api/stream.html#stream_writable_write_chunk_encoding_callback




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.