Stream writable.cork() and uncork() Method in Node.js


The writable.cork() method is used for forcing all the written data to be buffered inside a memory. This buffered data will only be removed from the buffer memory after stream.uncork() or stream.end() method have been called.

Syntax

cork()

writeable.cork()

uncork()

writeable.uncork()

Parameters

Since it buffers the written data. Only parameter that's needed will be the writable data.

Example

Create a file with name – cork.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −

node cork.js

cork.js

 Live Demo

// Program to demonstrate writable.cork() method
const stream = require('stream');

// Creating a data stream with writable
const writable = new stream.Writable({
   // Writing the data from stream
   write: function(chunk, encoding, next) {
      // Converting the data chunk to be displayed
      console.log(chunk.toString());
      next();
   }
});

// Writing data
writable.write('Hi - This data is printed');

// Calling the cork() function
writable.cork();

// Again writing some data
writable.write('Welcome to TutorialsPoint !');
writable.write('SIMPLY LEARNING ');
writable.write('This data will be corked in the memory');

Output

C:\home
ode>> node cork.js Hi - This data is printed

Only the data written between the cork() method will be printed while the remaining data will be corked in the buffer memory. Below example show how to uncork the above data from buffer memory.

Example

Let's take a look at one more example on how to uncork() - uncork.js

 Live Demo

// Program to demonstrate writable.cork() method
const stream = require('stream');

// Creating a data stream with writable
const writable = new stream.Writable({
   // Writing the data from stream
   write: function(chunk, encoding, next) {
      // Converting the data chunk to be displayed
      console.log(chunk.toString());
      next();
   }
});

// Writing data
writable.write('Hi - This data is printed');

// Calling the cork() function
writable.cork();

// Again writing some data
writable.write('Welcome to TutorialsPoint !');
writable.write('SIMPLY LEARNING ');
writable.write('This data will be corked in the memory');

// Flushing the data from buffered memory
writable.uncork()

Output

C:\home
ode>> node uncork.js Hi - This data is printed Welcome to TutorialsPoint ! SIMPLY LEARNING This data will be corked in the memory

The complete data from above example is displayed once the buffered memory is flushed using the uncork() method.

Updated on: 20-May-2021

464 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements