The event system helps programs respond to actions or changes quickly and easily. It makes your code listen and react like a conversation.
0
0
Why the event system matters in Node.js
Introduction
When you want your program to do something after a user clicks a button.
When you need to handle data arriving from a file or network without stopping everything else.
When you want different parts of your program to talk to each other without being tightly connected.
When you want to run code only after something important happens, like a timer finishing.
When building servers that handle many requests at the same time without waiting.
Syntax
Node.js
const EventEmitter = require('events'); const emitter = new EventEmitter(); // Listen for an event emitter.on('eventName', () => { console.log('Event happened!'); }); // Trigger the event emitter.emit('eventName');
EventEmitter is the core class that lets you create and handle events.
on sets up a listener that waits for the event.
Examples
This listens for a 'greet' event and prints 'Hello!' when it happens.
Node.js
emitter.on('greet', () => { console.log('Hello!'); }); emitter.emit('greet');
once listens only for the first time the event happens, then stops listening.Node.js
emitter.once('onlyOnce', () => { console.log('This runs just once'); }); emitter.emit('onlyOnce'); emitter.emit('onlyOnce');
You can send data with events. Here, the listener gets a message and prints it.
Node.js
emitter.on('data', (message) => { console.log('Received:', message); }); emitter.emit('data', 'Node.js is cool!');
Sample Program
This example shows a Door that can open. When it opens, it triggers an event. The program listens for that event and then welcomes you.
Node.js
const EventEmitter = require('events'); class Door extends EventEmitter { open() { console.log('Door is opening...'); this.emit('open'); } } const door = new Door(); door.on('open', () => { console.log('The door was opened. Welcome!'); }); door.open();
OutputSuccess
Important Notes
Events let your program do many things at once without waiting.
Use events to keep your code organized and easy to change.
Remember to remove listeners if they are no longer needed to avoid memory issues.
Summary
Events help programs react to actions or changes smoothly.
The event system keeps code flexible and easy to manage.
Node.js uses events a lot to handle many tasks at the same time.