Skip to content
Related Articles

Related Articles

Node.js | Stream writable.cork() Method
  • Last Updated : 25 Feb, 2020

The writable.cork() method is an inbuilt application programming interface of Stream module which is used to write every data into the buffer memory. When we use stream.uncork() or stream.end() methods then the buffer data will be flushed.

Syntax:

writable.cork() 

Parameters: This method does not accept any parameters.

Return Value: If this method is used then the data written after this method is not displayed in the output as these data are stored in the memory and can be again shown using some other specific methods.

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



Example 1:




// Node.js program to demonstrate the     
// writable.cork() method  
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();
  }
});
  
// Writing data
writable.write('hi');
  
// Calling cork() function
writable.cork();
  
// Again writing some data
writable.write('hello');
writable.write('world');

Output:

hi
true

Here, in the above example the data written before cork() method is only displayed and the data written after it is corked i.e. stored in the memory.

Example 2:




// Node.js program to demonstrate the     
// writable.cork() method  
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();
  }
});
  
// Writing data
writable.write('hi');
  
// Again writing some data
writable.write('hello');
writable.write('world');
  
// Calling cork() function
writable.cork();

Output

hi
hello
world

In the above example, the cork() method is written at last so, none of the data is being stored in the memory. Therefore, all the written data is displayed in the output.

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :