We can use the readable.pause()
method to stop the flow of data
events. This method pauses the reading of data from a file. Any data that exists during this pause operation can be found in the internal buffer.
readable.pause()
This method has no parameters.
Calling this method halts the reading of data unless readable.resume()
is called to resume the process. Nothing is explicitly returned.
A user can reverse the
pause()
operation using thereadable.resume()
method.
Let’s have a look at a coding example to understand the use of readable.pause()
. The file input.txt
is read into the stream. As long as the readable is on
, the stream prints this data received from the file. We then pause the readable stream for 5 seconds using timeout method. Lastly, we call .resume()
method to continue flowing the data and printing it in the console.
// fs module for file reading/writingconst fs = require('fs');// readable stream to read data from file.const readable = fs.createReadStream("input.txt");readable.on('data', (chunk) => {console.log(`Received: ${chunk}`);// Now let's pause.readable.pause();// the operation is paused for 5 seconds.console.log('The flow of data is paused for 5 seconds.');// Using setTimeout function to wait for 5 secondssetTimeout(() => {console.log('Thank you for waiting!');// call resume to start the flow.readable.resume();}, 5000);});
Free Resources