Immediately following the previous section, let’s analyze the code:
The first line requests (requires) 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, which has a method called listen. This method has a numerical parameter that specifies the port number that the HTTP server listens for.
To improve readability, let's change this code.
Original code:
The code copy 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:
The code copy 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 to perform callbacks when a corresponding event occurs. We call this event-driven callbacks.
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: the request information received;
response: The response made 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 content-type (content-type)
2. Use the response.write() function to send the text "Hello World" in the corresponding HTTP body.
3. Call response.end() to complete the response.
Does this analysis deepen your understanding of this code?
In the next section, let’s learn about the modularity of nodejs’ code.