Home  >  Article  >  Web Front-end  >  Easily create nodejs server (2): Analysis of the composition of nodejs server_node.js

Easily create nodejs server (2): Analysis of the composition of nodejs server_node.js

WBOY
WBOYOriginal
2016-05-16 16:25:541012browse

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:

Copy code The 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);

can be rewritten as:

Copy code The 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 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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn