Easy creation of nodejs servers (2): Component Analysis of nodejs servers,
Next to the previous section, let's analyze the Code:
The http module that comes with the first line request (require) Node. js and assigns it to the http variable.
Next, we will call the function createServer provided by the http module.
This function will return an object, which has a method called listen. This method has a numeric parameter that specifies the port number listened by the HTTP server.
To improve readability, let's modify this code.
Original code:
Copy codeThe Code is as follows:
Var http = require ("http ");
Http. createServer (function (request, response ){
Response. writeHead (200, {"Content-Type": "text/plain "});
Response. write ("Hello World ");
Response. end ();
}). Listen (8888 );
It can be rewritten:
Copy codeThe Code is as follows:
Var http = require ("http ");
Function onRequest (request, response ){
Response. writeHead (200, {"Content-Type": "text/plain "});
Response. write ("Hello World ");
Response. end ();
}
Http. createServer (onRequest). listen (8888 );
We define an onRequest () function and pass it as a parameter to createServer, similar to a callback function.
We pass a function to a method. This method calls this function for callback when a corresponding event occurs. We call this event-driven callback.
Next, let's take a look at the body of onRequest (). When the callback is started and our onRequest () function is triggered, two parameters are passed in: request and response.
Request: the information of the received request;
Response: The response after receiving the request.
Therefore, the operation performed by this code is:
When receiving a request,
1. Use the response. writeHead () function to send an HTTP status 200 and HTTP header content type (content-type)
2. Use the response. write () function to send the text "Hello World" in the HTTP body ".
3. Call response. end () to complete the response.
Does this analysis deepen your understanding of this code?
Next, let's take a look at the code modularization of nodejs.