Ask Your Question
0

How can one listen to events in node.js using a callback parameter?

asked 2023-07-21 13:55:30 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-07-21 14:14:02 +0000

plato gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-21 13:55:30 +0000

Seen: 28 times

Last updated: Jul 21 '23