Immediately in the previous section, let's Analyze the code:
The first line request (require) Node.js the self-contained HTTP module and assigns it to the HTTP variable.
Next we call the function provided by the HTTP module: Createserver.
This function returns an object that has a method called Listen, which has a numeric parameter that specifies the port number that the HTTP server listens to.
To improve readability, let's change the code.
The original code:
Copy Code code as follows:
var http = require ("http");
Http.createserver (function (request, response) {
Response.writehead ({"Content-type": "Text/plain"});
Response.Write ("Hello World");
Response.End ();
}). Listen (8888);
Can be rewritten as:
Copy Code code as follows:
var http = require ("http");
function onrequest (request, Response) {
Response.writehead ({"Content-type": "Text/plain"});
Response.Write ("Hello World");
Response.End ();
}
Http.createserver (ONrequest). Listen (8888);
We defined a onrequest () function and passed it as a parameter to the Createserver, similar to the callback function.
We pass a function to a method that calls this function for callback when there is a corresponding event, which we call an event-driven callback.
Next we 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: The requested information received;
Response: The response that was made after the request was received.
So this code does the following:
When the request is received,
1. Use the Response.writehead () function to send a content type of HTTP status 200 and HTTP headers (content-type)
2. Use the Response.Write () function to send the text "Hello World" to the HTTP corresponding body.
3, call Response.End () to complete the response.
Does this analysis deepen your understanding of this piece of code?
In the next section, let's take a look at the Nodejs code modularity.