How to create a custom event in Node js
- 2022年6月28日
- 技術情報
Today, I would like to share about creating a custom event in Node js. Let’s take a look.
In Node js, there is a built-in module named ‘events’. With this module, you can create a custom event and bind the custom event process function with the event. Let’s write some codes.
1. include ‘events’ module
let events = require(‘events’);
2. create an EventEmitter object
let eventEmitter = new events.EventEmitter();
3. create a function that will be triggerd as a callback function when the event happens
let connection_start_handler = () => {
console.log('Connection started')
}
4. register the event with the callback function.
eventEmitter.on('connection_start', connection_start_handler);
5. Trigger the event. This will execute the callback function connection_start_handler().
eventEmitter.emit('connection_start')
Then we create a file with the above code and run with the following command to see output.
$ node custom_event.js
The output is
Connection started.
This is all for now. Hope you enjoy that.
By Asahi
waithaw at 2022年06月28日 10:00:00