node. JS Development Primer-helloworld Re-analysis

Source: Internet
Author: User
Tags function prototype

Getting Started with node. JS (1) We implemented a simple HelloWorld Web site with an HTTP module, and this time we'll examine the code carefully to see more details.

First look at the HTTP version of the HelloWorld code:

The code is so simple:

// 引入http模块var http = require("http"); // 创建server,指定处理客户端请求的函数http.createServer(    function(request, response) {         response.writeHead(200, {"Content-Type": "text/plain"});         response.write("Hello World!");         response.end();     }).listen(8000); console.log("Hello World is listening at port 8000");
HelloWorld Code Analysis

Well, from now on, we're going to analyze our HelloWorld by line.

Introducing Modules
var http = require("http");

The Require method is used to introduce a module whose parameters are the name of the module. such as the file system module, you can introduce:

var fs = require("fs");

We can use the require () method as a global method, but in fact it is more like a local method belonging to a module, and its documentation is referenced here: https://nodejs.org/api/globals.html.

The Require method returns an instance of a module, such as require ("http"), returning an HTTP instance. The reference documentation for the HTTP instance is here: https://nodejs.org/api/http.html.

We see that the HTTP module has a method Createserver (), which involves our second line of code.

Creating a server

The HTTP module's Createserver () method, which accepts a method as a parameter, is prototyped as:

http.createServer([requestListener])

Requestlistener is a method that will be associated with HTTP. The request event for the server class is associated. This allows the requestlistener to be called when a client request arrives.

The Requestlistener has two parameters, and the function prototype is as follows:

function (request, response) { }

The type of the first parameter request is HTTP. Incomingmessage, the readable stream interface is implemented. The type of the second parameter is HTTP. Serverresponse, the writeable stream interface is implemented. Stream's API is here: https://nodejs.org/api/stream.html. At the same time, request and response are eventemitter and can launch specific events. Eventemitter's API is here: Https://nodejs.org/api/events.html#events_class_events_eventemitter, Later we will talk about how to use Eventemitter to launch events and handle events.

Look again at the code we created for the server:

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

Http.createserver returns a Http.server instance, Http.server's Listen method allows the server to listen on a port, which is 8000 in the example.

As you can see, we provide an anonymous function to the Createserver method. In this method, we write the "Hello world!" back to the client through the response parameter News.

Parsing client requests

Earlier we analyzed the Http.createserver method, whose parameters are a method with two parameters, one representing the request sent by the client, and one representing the response to be written back to the client. Let's take a look at the request parameter.

Request is HTTP. Incomingmessage example, through this example, we can get the request parameters, such as HTTP method, HTTP version, URL, head, etc., the specific API here: HTTPS://NODEJS.ORG/API/HTTP.HTML#HTTP_ Http_incomingmessage.

We can see (Save as Helloworld2.js) by modifying the helloworld.js. The code is as follows:

// 引入http模块var http = require("http"); // 创建server,指定处理客户端请求的函数http.createServer(    function(request, response) {         console.log("method - " + request.method);        console.log("version - " + request.httpVersion);        console.log("url - " + request.url);        response.writeHead(200, {"Content-Type": "text/plain"});         response.write("Hello World!");         response.end();     }).listen(8000); console.log("Hello World start listen on port 8000");

As you can see, I use the console object to output some debugging information, print the HTTP method, version, URL and other information. You can execute node helloworld2.js, the browser accesses http://localhost:8000, and then run to the command line to see what information is being exported, and here I am:

Send a response to the client

Our simple HelloWorld has been able to send some response data to the client, you can see "Hello world!" in the browser Words. This response is via HTTP. Serverresponse instance response sent to the client.

http. Serverresponse is also a stream, or a eventemitter. We use it to return HTTP status codes, data, HTTP headers, and so on.

Explain some basic concepts.

The HTTP response consists of the status line + header + data, with the following basic structure:

| —————————————————— |
| HTTP Version|status code|message|
| ————————————————— –|
| Header-name-1: Value |
| ————————————————— –|
| Header-name-2: Value |
| ————————————————— –|
| Header-name-2: Value |
| ————————————————— –|
| Blank line (CRLF) |
| ————————————————— –|
| optional data (body) |
| ————————————————— –|

HTTP status Code

is 200, 301, 302, 403, 404 such as the number, by the server to tell the client the state of the request, is successful, or can not find the file, or ... See here http://kb.cnblogs.com/page/130970/.

In the node. JS HTTP module, the status line is written to the client through the Http.serverresponse Writehead method. The Writehead method is prototyped as follows:

response.writeHead(statusCode[, statusMessage][, headers])

The first parameter of this method is StatusCode, which is the number 200, 403, and the remaining parameters are optional. The last parameter is headers, where you can use the JSON object notation to write some HTTP headers, such as: {"Content-type": "Text/plain", "Content-length": 11}. The first optional parameter, StatusMessage, is used to specify a status description message, which may not be filled in.

HTTP Header

The head is some key-value, for example, we see in the HelloWorld "Content-type", is used to describe the data type of the head tag, corresponding to the possible text files, images, video, binary and so on. A similar "Content-length" is used to specify the length of the data. There are many more, such as "Date", "Connection" and so on. Refer to the previous link for more details.

The head can also use HTTP. The Serverresponse response.setheader (name, value) method is set separately, and one HTTP header can be set at a time.

Data

After the head is the data, some status code, such as 200, the subsequent will have some data. And some, like 301, 404, 403, 500 and the like, most have no data.

Data is passed through HTTP. The Write method of the Serverresponse is written back to the client, such as this:

response.setHeader("Content-Type", "text/html");

One thing to mention here is that there are two common ways to encode data in http:

    • Set Content-length to transfer fixed-length data
    • Set transfer-encoding head to chunked, chunked transfer data

Like our current HelloWorld example, without setting the Content-length header, node. JS's HTTP module defaults to chunked encoding.

We use Chrome's developer tools to view network data, which we can clearly see. As shown in the following:

The three places I marked are the HTTP header information that the HelloWorld example passes to the browser.

We pass HTTP. The Write method of Serverresponse writes data to the client. You can write all the data at once, or you can separate the data for multiple writes. When the amount of data to be transmitted is large, it is reasonable to write several times, for example, if you send large files to the client, it is more suitable for multiple writes, and can take advantage of the asynchronous features of node. js to get good performance.

OK, this time we have a little detailed analysis of HelloWorld, next time, we implement a simple file server, will use more node. JS modules and APIs.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

node. JS Development Primer-helloworld Re-analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.