How to create a custom event in Node js

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



アプリ関連ニュース

お問い合わせはこちら

お問い合わせ・ご相談はお電話、またはお問い合わせフォームよりお受け付けいたしております。

tel. 06-6454-8833(平日 10:00~17:00)

お問い合わせフォーム