Главная » Error » Node event error

Node event error

At its core, Node.js is an open source runtime environment built for running JavaScript applications on the server side. It provides an event-driven, non-blocking (asynchronous) I/O and cross-platform runtime environment for building highly scalable server-side applications using JavaScript.

This is not going to be an introduction guide to Node.js; to learn more, you can check out the official docs or video tutorials on YouTube. Instead, we’ll discuss how to handle and dispatch events in Node.js.

Event: ‘error’ When an error occurs within an EventEmitter instance, the typical action is for an ‘error’ event to be emitted. If an EventEmitter does not have at least one listener registered for the ‘error’ event, and an ‘error’ event is emitted, the error is thrown, a stack trace is printed, and the Node.js process exits.

eventEmitter.on(‘error’, listener)

// Importing events

const EventEmitter = require(‘events’);

// Initializing event emitter instances

var eventEmitter = new EventEmitter();

// Register to error

eventEmitter.on(‘error’, (err) => {

    console.error(‘whoops! there was an error’);

});

// Register to newListener

eventEmitter.on( ‘newListener’, (event, listener) => {

    console.log(`The listener is added to ${event}`);

});

 // Register to removeListener

eventEmitter.on( ‘removeListener’, (event, listener) => {

    console.log(`The listener is removed from ${event}`);

});

 // Declaring listener fun1 to myEvent1

var fun1 = (msg) => {

    console.log(“Message from fun1: ” + msg);

};

 // Declaring listener fun2 to myEvent2

var fun2 = (msg) => {

    console.log(“Message from fun2: ” + msg);

};

 // Listening to myEvent with fun1 and fun2

eventEmitter.on(‘myEvent’, fun1);

eventEmitter.on(‘myEvent’, fun2);

 // Removing listener

eventEmitter.off(‘myEvent’, fun1);

// Triggering myEvent

eventEmitter.emit(‘myEvent’, ‘Event occurred’);

 // Triggering error

eventEmitter.emit(‘error’, new Error(‘whoops!’));

Output:

The listener is added to removeListener

The listener is added to myEvent

The listener is added to myEvent

The listener is removed from myEvent

Message from fun2: Event occurred

whoops! there was an error

Error events within Node.js

Errors during development are inevitable but can be handled properly in Node.js. Apart from the try-catch block, Node can also listen to an error event and carry out several actions whenever an error occurs. If an EventEmitter does not have at least one listener registered for the error event, and an error event is emitted, the error is thrown, a stack trace is printed, and the Node.js process exits.

To prevent crashing the Node.js process, it is recommended to always add error event listeners to your Node application

1 Звезда2 Звезды3 Звезды4 Звезды5 Звезд (Пока оценок нет)
Загрузка...

Добавить комментарий

Ваш адрес email не будет опубликован.

Adblock
detector