Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To listen to events in Node.js using a callback parameter, you can use the on method that is available for various modules. The on method allows you to register a callback function that will be executed when the event is emitted.

Here is an example of listening to an event in the HTTP module using a callback function:

const http = require('http');

const server = http.createServer();

server.on('request', (req, res) => {
  console.log('Request received');
  res.end('Hello World!');
});

server.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

In this example, the createServer method creates an HTTP server, and the on method is used to register a callback function that will be executed when a request event is emitted. The callback function simply logs a message to the console and sends a response to the client with the message "Hello World!". The listen method is called to start the server listening on port 3000, and another callback function is passed to it to log a message to the console when the server starts listening.

There are many different modules in Node.js that emit events, and they each have their own specific event names and callback parameters. When using a module that emits events, you should consult the documentation to determine the appropriate event names and callback parameters to use.