This is the 24th day of my participation in the August More Text Challenge

Node event trigger

  • In the browser, we can handle many user interactions through events, such as mouse clicks, keyboard button presses, mouse movements, and so on.
  • On the back end, Node.js also provides the option to build a similar system using the Events module.
  • The Events module provides the EventEmitter class for processing events.
const EventEmitter = require('events')
const eventEmitter = new EventEmitter()
Copy the code
  • The object is also exposedonemitMethods, and some other methods:
  • emit Used to trigger events.
  • onUsed to add callback functions (when the event is raised)
  • once(): Adds a single listener.
  • removeListener() / off(): Removes the event listener from the event.
  • removeAllListeners(): Removes all listeners for the event.

Setting up the HTTP Server

  • The HTTP module provided by Node is used to set up the HTTP server.
const http = require('http')
const port = 3000
const server = http.createServer((req, res) = > {

      res.statusCode = 200
      res.setHeader('Content-Type'.'text/plain')
      res.end('Hello world \n')
})

server.listen(port, () = > {
  console.log(The server runs in http://${hostname}:${port}/ `)})Copy the code

The above code creates a basic HTTP Web server. The server is set up to listen on the specified port 3000. The LISTEN callback is called when the server is ready.

The incoming callback function is executed each time a request is received. Each time a new request is received, the Request event is invoked and provides two objects: a request (http.incomingMessage object) and a response (http.serverResponse object).

Request provides the details of the request. It provides access to the request header and requested data.

Response is used to construct data to be returned to the client.

For example, we set statusCode 200 in the code above to indicate a successful response. Set the setHeader.

Also, finally, we need to close the response at the end, and we can add the content as an argument to the end() method. Such as:

res.end('I'm gonna close the response.')
Copy the code