Node.js Events
Node.js uses an event-driven architecture to allow asynchronous I/O operations. In this architecture, an object that emits an event is called an "event emitter", while an object that listens for events is called an "event listener". In this tutorial, we'll discuss how to use events in Node.js.
Syntax
The syntax for creating an event emitter in Node.js is as follows:
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
// Listener function
const listenerCallback = () => {
console.log('Event triggered');
};
// Add listener to emitter
myEmitter.on('event-name', listenerCallback);
// Emit event
myEmitter.emit('event-name');
Example
Let's say we want to create an event emitter that emits a "pizza-ready" event when a pizza is ready. Here's how we can implement it:
const EventEmitter = require('events');
const pizzaEmitter = new EventEmitter();
// Listener function
const listenerCallback = () => {
console.log('Pizza is ready');
};
// Add listener to emitter
pizzaEmitter.on('pizza-ready', listenerCallback);
// Simulate pizza being made
setTimeout(() => {
pizzaEmitter.emit('pizza-ready');
}, 5000);
We added a listener to the pizzaEmitter object that listens for the "pizza-ready" event and logs "Pizza is ready" to the console. We then simulate the pizza being made by setting a timeout of 5 seconds and emitting the "pizza-ready" event.
Output
When we run the example code above, we will see the following output:
Pizza is ready
This is because the listener function was triggered when the "pizza-ready" event was emitted.
Explanation
In the example above, we created an event emitter object called "pizzaEmitter". We then added a listener function to the emitter that listens for the "pizza-ready" event. When the "pizza-ready" event is emitted, the listener function is called, and "Pizza is ready" is logged to the console.
We then simulated the pizza being made by setting a timeout and emitting the "pizza-ready" event.
Use
Events are useful for handling asynchronous operations in Node.js. You can use events to listen for changes in a file, to handle HTTP requests, or to handle user input, among other things.
Important Points
- You can add multiple listener functions to an event emitter by calling the on() function multiple times with different listener functions.
- You can remove a listener function from an event emitter by calling the removeListener() function.
- Events in Node.js are not browser events. They are a Node.js construct for handling asynchronous I/O operations.
Summary
In this tutorial, we discussed how to use events in Node.js. We covered the syntax, example, output, explanation, use, and important points of events in Node.js. With this knowledge, you can now use events in your Node.js code to handle asynchronous operations.