Following the previous section, let’s analyze the code:
The first line requests the http module that comes with Node.js and assigns it to the http variable.
Next we call the function provided by the http module: createServer.
This function will return an object. This object has a method called listen. This method has a numerical parameter that specifies the port number that the HTTP server listens on.
To improve readability, let’s change this code.
Original code:
can be rewritten as:
We define an onRequest() function and pass it to createServer as a parameter, similar to a callback function.
We pass a function to a method, and this method calls this function to perform a callback when a corresponding event occurs. We call this an event-driven callback.
Next let’s take a look at the main part of onRequest(). When the callback is started and our onRequest() function is triggered, two parameters are passed in: request and response.
request: received request information;
response: The response after receiving the request.
So what this code does is:
When a request is received,
1. Use the response.writeHead() function to send an HTTP status 200 and the content-type of the HTTP header
2. Use the response.write() function to send the text "Hello World" in the HTTP corresponding body.
3. Call response.end() to complete the response.
Did this analysis deepen your understanding of this code?
In the next section, we will learn about the code modularization of nodejs.