Show List

Event-driven programming

Event-driven programming is a programming paradigm in which the flow of the program is determined by events or changes in the state of the application. In event-driven programming, an event is a signal that something has happened, and the event listener is a piece of code that responds to the event by executing a callback function.

Node.js uses an event-driven, non-blocking I/O model, which makes it a great platform for event-driven programming. In Node.js, the EventEmitter class is used to create and manage events and event listeners.

Here's a simple example of event-driven programming in Node.js:

const EventEmitter = require('events');

// create a custom event emitter
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();

// create an event listener
myEmitter.on('event', (a, b) => {
  console.log(a, b, this);
});

// emit the event
myEmitter.emit('event', 'a', 'b');

In this example, a custom event emitter is created by extending the EventEmitter class. An event listener is then attached to the event emitter using the on method. The emit method is used to trigger the event, and the event listener is executed, logging the arguments and the context to the console.

Here's another example of event-driven programming in Node.js, using the http module to create a simple HTTP server:

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello World\n');
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

// add an event listener for the "request" event
server.on('request', (req, res) => {
  console.log('Request received:', req.url);
});

In this example, the http module is used to create an HTTP server. An event listener is attached to the server using the on method to handle the request event, which is emitted whenever a client makes a request to the server. The event listener logs the URL of the incoming request to the console.

Event-driven programming is a powerful tool for building scalable and responsive applications in Node.js. These examples should give you a basic understanding of how event-driven programming works in Node.js.



Next: Express


    Leave a Comment


  • captcha text