In Node.js, an event is an action that can be listened to and acted upon. Imagine events as a notification system. Whenever something happens, like a file read completion or a request received, Node.js triggers an event that you can respond to.
Node.js has a built-in module called events, and the most important class in this module is EventEmitter. It allows you to define and handle events.
Let’s see how to create an event emitter.
const EventEmitter = require('events'); const myEmitter = new EventEmitter(); // Register an event listener myEmitter.on('greet', () => { console.log('Hello there!'); }); // Emit the event myEmitter.emit('greet');
In this example, we registered a listener for the greet event and then emitted the event. The result is a simple "Hello there!" printed to the console.
You can also pass arguments when emitting events. This is helpful when you need to pass data.
myEmitter.on('sayHello', (name) => { console.log(`Hello, ${name}!`); }); myEmitter.emit('sayHello', 'Alice');
Now, when we emit the sayHello event, it greets Alice.
Let’s create a basic HTTP server and demonstrate how events come into play. In Node.js, the http module uses events extensively. Every time a request hits the server, it triggers an event.
const http = require('http'); // Create a server const server = http.createServer((req, res) => { if (req.url === '/') { res.write('Hello World'); res.end(); } }); // Register an event listener for 'request' server.on('request', (req, res) => { console.log(`Received request for ${req.url}`); }); // Start the server server.listen(3000, () => { console.log('Server is running on port 3000'); });
In this example:
You can create custom events within your server code to handle specific tasks. Here's an example of emitting a custom event when a client connects.
const EventEmitter = require('events'); const http = require('http'); // Create an event emitter instance const myEmitter = new EventEmitter(); // Create a server const server = http.createServer((req, res) => { res.write('Hello Client'); res.end(); // Emit a custom event on each request myEmitter.emit('clientConnected', req.url); }); // Listen for the custom 'clientConnected' event myEmitter.on('clientConnected', (url) => { console.log(`A client connected to ${url}`); }); // Start the server server.listen(3000, () => { console.log('Server is running on port 3000'); });
In this example:
Events are at the heart of Node.js, making it powerful for handling asynchronous operations, especially in the context of servers. By mastering events, you’ll have a strong foundation for building scalable and efficient applications.
Thank you for reading, and happy coding! ?
The above is the detailed content of Understanding Events in Node.js with Simple Code Examples - Node.js Tutorial - Part 6. For more information, please follow other related articles on the PHP Chinese website!