Languages
[Edit]
EN

Node.js - pass arguments to event emitter

0 points
Created by:
evangeline
330

In this article, we would like to show you how to pass arguments to event emitter in Node.js.

Quick solution:

const EventEmitter = require('events');

const eventEmitter = new EventEmitter();

eventEmitter.on('eventName', (arg) => {
    console.log(arg);
});

eventEmitter.emit('eventName', value);

 

Practical example

In this example, we pass the databaseName argument to the events callback function to display connection information on the event trigger.

// import module
const EventEmitter = require('events');

// create EventEmitter object
const eventEmitter = new EventEmitter();

// add callback function to be executed on event trigger
eventEmitter.on('connect', (database) => {
    console.log(`Connected to ${database}.`);
});

// example data
const databaseName = 'myDatabase';

// trigger the event with passed argument
eventEmitter.emit('connect', databaseName);

Output:

Connected to myDatabase.

Related posts

References

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join