Node Js has built in event module to handle event. I expect that we all know what the event is. Actually, event create an action when user triggered. Events can be user-generated, such as keystrokes and mouse clicks. But these events are built in. We can't make our event as our choice. In node js, we can make our event. Node Event by clicking this you can get the official docs.
Node Event
One of the core concepts of Node.js is events. Event Emitter plays a vital role in Node.js Event-Driven Architecture.
How does it work?
Node Emit works in three ways.
- Event Emitter emits the data in an event called message
- A Listened is registered on the event message
- when the message event emits some data, the listener will get the data.
EventEmitter methods and description
- on(): on(event, listener), by this method we can add event listener. It is just like 'addListener' keyword in JavaScript.
- emit(): emit(event, arg1, arg2), by this event we call the specified event listener. It is just like 'onclick' keyword in JavaScript.
- once(): once(event, listener), by this method the event is called for one time and after that it will be removed.
- addListener(): addListener(event, listener), by this method the event is checked if it is registered or not.
- removeListener(): removeListener(event, listener), by this method the event is removed for listener.
Example:
const EventEmitter = require("events")
const emitter = new EventEmitter()
emitter.on("message", (arg) => {
console.log("subsribed", message)
})
emitter.emit("message", "Welcome to my blog.")
From the above example, we can say that EventEmitter is a built-in class of event in Node JS. Normally, we declare our variable name with lower case at start, but here we should start with upper case letter in declaring event emitter. When we import 'events' class where methods are written. After creating an object, we can access these methods. So, 'emitter' is a object of that particular class, and it accesses the on() method and emit() method over there.
Use Case
At first, create a file named "timer.js". The code will be the following example given below.
const EventEmitter = require("events")
class Timer extends EventEmitter {
closeIt('close', msg) {
this.emit('close', msg)
}
}
module.exports = Timer
Here, we can see, Timer extends the EventEmitter class and the method called closeIt takes event and message as an argument.
Now create 'app.js' file and write this code.
const Timer = require("./Timer")
const timer = new Timer()
timer.on("close", arg => {
console.log("Listened value: ", arg)
})
timer.closeIt("close: ", 'Time out ! Server will be closing soon...')
Top comments (0)