Node.js Stream readable.resume() Method

Node.js streams are powerful tools for handling data transfer efficiently, especially when dealing with large datasets or real-time data. The readable.resume() method is a part of the readable stream interface, playing a crucial role in managing the flow of data. This article will delve into what readable.resume() does, how it works, and when to use it.

Table of Content

  • What is a Readable Stream
  • What is readable.resume( )
  • How Does readable.resume( ) Work

What is a Readable Stream

In Node.js, a readable stream is an abstraction for a source of data that you can read from. Examples include reading from a file, receiving HTTP requests, or processing data from other data sources. Readable streams are instances of the Readable class, which is part of the stream module.

Readable streams can operate in two modes:

  • Paused Mode: The stream does not emit data events and you must explicitly call methods like read() to get data.
  • Flowing Mode: The stream emits data events as soon as data is available, and it is automatically consumed.

What is readable.resume( )

The readable.resume() method is used to switch a readable stream into flowing mode. When a stream is in flowing mode, data is read from the underlying source and provided to your program without requiring explicit calls to read().

How Does readable.resume( ) Work ?

When you call readable.resume(), the stream starts emitting data events, delivering chunks of data to the provided listeners. This method is particularly useful when you want to process data as it becomes available, rather than waiting for the entire dataset to be loaded.

Syntax:


readable.resume()

In the below example:

  • A readable stream is created from a file named example.txt.
  • The data event listener logs each chunk of data received.
  • The end event listener logs a message when the stream ends.
  • The resume() method is called to switch the stream to flowing mode and start processing data immediately.
const fs = require('fs');

// Create a readable stream from a file
const readableStream = fs.createReadStream('example.txt');

// Handle the data event
readableStream.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
console.log(chunk.toString());
});

// Handle the end event
readableStream.on('end', () => {
console.log('No more data.');
});

// Resume the stream to start flowing data
readableStream.resume();

Example 1: Below examples illustrate the use of readable.resume() method in Node.js.

javascript
// Node.js program to demonstrate the     
// readable.resume() method  

// Including fs module
const fs = require('fs');

// Constructing readable stream
const readable = fs.createReadStream("input.text");
readable.on('data', (chunk) => {
  console.log(`${chunk}`);
});

// Calling pause method
readable.pause();

// Calling resume method
readable.resume();

console.log("Data starts flowing again!!");

Output:

Data starts flowing again!!
Hello!!!

Example 2: Below examples illustrate the use of readable.resume() method in Node.js.

App.js
// Node.js program to demonstrate the     
// readable.resume() method  

// Include fs module
const fs = require('fs');

// Create readable stream
const readable = fs.createReadStream("input.text");

// Handling data event
readable.on('data', (chunk) => {
  console.log(`${chunk}`);

  // Calling pause method
  readable.pause();

  // After this any data will be displayed 
  // after 3 sec.
  console.log('No additional data will be '
             + 'displayed for 3 seconds.');

  // Using setTimeout function
  setTimeout(() => {
    console.log('Now data starts flowing again.');

    // Calling resume method
    readable.resume();
  }, 3000);
});

// Displays that program 
// is ended
console.log("Program ends!!");

Output:

Program ends!!
Hello!!!
No additional data will be displayed for 3 seconds.
Now data starts flowing again.

When to Use readable.resume()

  • Processing Data in Real-Time: Use resume() when you need to handle data as soon as it arrives, such as streaming media or real-time analytics.
  • Avoiding Memory Overhead: By processing data in chunks, you avoid loading the entire dataset into memory, which is beneficial for handling large files.
  • Compatibility with Event Listeners: If you have set up data event listeners and want to ensure they start receiving data, resume() will trigger the flow.

Important Considerations

  • Error Handling: Always attach an error event listener to handle potential errors in the stream.
  • Backpressure: While resume() switches the stream to flowing mode, be aware of backpressure mechanisms that help manage the rate of data flow, preventing overwhelming the application.
  • Pausing a Stream: If you need to temporarily stop the flow of data, you can call readable.pause().

Conclusion

The readable.resume() method is a crucial tool in the Node.js streaming API, enabling efficient, real-time data processing. By understanding how to switch between paused and flowing modes, you can better manage data flow and build performant, scalable applications. Remember to handle errors gracefully and consider backpressure when dealing with high-throughput data streams.