The cork()
method is a built-in method in Stream’s Writable
module of NodeJS.
This method is used to pass data into a buffer memory. Writing the method writable.cork()
(where writable is an object of stream.Writable
) in the code will write all the specified data into the buffer memory.
writable.cork()
// writable is an object of stream.Writable
Using this method will make sure that any data written is not displayed in the console, as it is part of the buffer memory. It can only be displayed when the buffer is flushed.
Lets look at a coding example for the cork()
method.
In line 27, the cork()
function is called, and all incoming data will be part of the buffer. Therefore, this corked data is only printed when the buffer is flushed.
// accessing streamconst stream = require('stream');// creating a Writable object along with a function.const writable = new stream.Writable({// Define a function to display the wrtiable datawrite: function(value, encoding, next) {// dislaying the address of data saved in memoryconsole.log(value);// displaying the actual data by converting it to stringconsole.log(value.toString());next();}});// write some datawritable.write('H');writable.write('E');writable.write('L');writable.write('L');writable.write('O');// cork() function is called, all incoming data will be// part of the buffer.writable.cork();// All incoming data is corked and part of buffer memory.writable.write('Welcome');writable.write('to');writable.write('Educative');
Free Resources