Node.js | Stream readable.destroy() Method

The readable.destroy() method is an inbuilt application programming interface of Stream module which is used to destroy the stream.

Syntax:

readable.destroy( error )

Parameters: This method accepts single parameter error which is optional and it emits an error while handling error event.

Return Value: If this method is used then the stream is destroyed and if the error parameter is passed as an argument then it emits an error event.

Below examples illustrate the use of readable.destroy() method in Node.js:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the     
// readable.destroy() method  
  
// Include fs module
const fs = require("fs");
  
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
  
// Instructions for reading data
readable.on('readable', () => {
  let chunk;
  
  // Using while loop and calling
  // read method with parameter
  while (null !== (chunk = readable.read(1))) {
  
    // Displaying the chunk
    console.log(`read: ${chunk}`);
  }
});
  
// Calling destroy method
readable.destroy();
  
// Displays that the stream is 
// destroyed
console.log("Stream destroyed");

chevron_right


Output:

Stream destroyed

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the     
// readable.destroy() method  
  
// Include fs module
const fs = require("fs");
  
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
  
// Instructions for reading data
readable.on('readable', () => {
  let chunk;
  
  // Using while loop and calling
  // read method with parameter
  while (null !== (chunk = readable.read())) {
  
    // Displaying the chunk
    console.log(`read: ${chunk}`);
  }
});
  
// Handling error event
readable.on('error', err => {
    console.log(err);
});
  
// Calling destroy method
// with parameter
readable.destroy(['error']);
  
// Displays that the stream is 
// destroyed
console.log("Stream destroyed");

chevron_right


Output:

Stream destroyed
[ 'error' ]

In the above example error event is emitted.

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




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.