Node.js Stream readable.destroy() Method
Last Updated :
12 Oct, 2021
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:
const fs = require( "fs" );
const readable = fs.createReadStream( "input.txt" );
readable.on( 'readable' , () => {
let chunk;
while ( null !== (chunk = readable.read(1))) {
console.log(`read: ${chunk}`);
}
});
readable.destroy();
console.log( "Stream destroyed" );
|
Output:
Stream destroyed
Example 2:
const fs = require( "fs" );
const readable = fs.createReadStream( "input.txt" );
readable.on( 'readable' , () => {
let chunk;
while ( null !== (chunk = readable.read())) {
console.log(`read: ${chunk}`);
}
});
readable.on( 'error' , err => {
console.log(err);
});
readable.destroy([ 'error' ]);
console.log( "Stream destroyed" );
|
Output:
Stream destroyed
[ 'error' ]
In the above example error event is emitted.
Reference: https://nodejs.org/api/stream.html#stream_readable_destroy_error
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...