Easily create nodejs server (2) : composition analysis of nodejs server

  • 2020-05-07 19:11:15
  • OfStack

Following the previous section, we will analyze the following code:

Line 1 requests (require) Node.js's 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 argument specifying the port number the HTTP server is listening to.

To improve readability, let's change this code by 1.

Original code:


var http = require("http");
http.createServer(function(request, response) {
 response.writeHead(200, {"Content-Type": "text/plain"});
 response.write("Hello World");
 response.end();
}).listen(8888);

can be rewritten as:


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 defined an onRequest() function and passed it as an argument to createServer, similar to a callback function.

We pass a function to a method that calls this function when an event occurs. We call this event-driven callback.

Next we look at the body of onRequest(). When the callback is started and our onRequest() function is triggered, two arguments are passed in: request and response.

request: received request information;

response: response to a request received.

So what this code does is:

When a request is received,

1. Use the response.writeHead () function to send 1 HTTP status 200 and HTTP header content type (content-type)

2. Use the response.write () function to send the text "Hello World" in the corresponding body of HTTP.

3. Call response.end () to complete the response.

Does this analysis deepen your understanding of the code?

In the next section we'll look at 1, code modularity for nodejs.


Related articles: