Node.js | Readable Stream error Event

The ‘error’ event in Readable stream can be emitted at any time. It takes place when the hidden stream is not able to generate data due to some hidden internal failure or when the implementation of stream pushes a chunk of data which is not valid. Moreover, a single Error object is passed as an argument to the listener callback.

Syntax:

Event: 'error'

Below examples illustrate the use of error event in Node.js:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the     
// readable error event
  
// Including fs module
const fs = require('fs');
  
// Constructing readable stream
const readable = fs.createReadStream("inpu.txt");
  
// Handling error event
readable.on("error", err => {
    console.log(err);
});
  
console.log("Done...");

chevron_right


Output:



Done...
{ [Error: ENOENT: no such file or directory, open 'inpu.txt'] errno: -2,
 code: 'ENOENT', syscall: 'open', path: 'inpu.text' }

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the     
// readable error event
  
// Including fs module
const fs = require('fs');
  
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
  
// Handling error event
readable.on("error", err => {
    console.log(err);
});
  
console.log("Done...");

chevron_right


Output:

Done...

Here, no error occurs so error event is not emitted.

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

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.