Nodejs learning item [Getting Started] _ node. js

Source: Internet
Author: User
Tags stream api
This article mainly introduces Nodejs learning item [Getting Started]. If you need it, refer I. Installation

First, download the installation from the http://nodejs.org. My version is 0.8.14. The installation is very simple. The next step is the next step. Then configure the installation directory in path. msi will install the npm (Node Package Manager) together.

My installation directory is C: \ Program Files (x86) \ nodejs. In this case, use the cmd command window.node -v,npm -vCommand to view the installed version

1.1. helloworld

Create a new file hello. js in the Node. js project directory and click a line of code in it.

console.log('hello, nodejs.') ;

Log on to the command line console, go to the Node. js project directory, and click "hello. js ".

The console outputs "hello, nodejs ."

1.2. web version of helloworld

Create an http. js file in the Node. js project directory. The Code is as follows:

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

Start the service in the command line and tap node http. js

Open the address bar of the browser and enter http: // localhost: 8000/. The Hello World is displayed! It is successful.

The node. js version must be synchronized with the API

The version number of node. js is regular. The even version is stable, and the odd version is unstable.

2 HelloWorld code analysis

Well, from now on, we will analyze our HelloWorld line by line.

Introduction module

var http = require("http");

The require method is used to introduce a module. The parameter is the name of the module. For example, the File System module can be introduced as follows:

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. For more information, see https://nodejs.org/api/globals.html.

The require method returns an instance of a module. For example, require ("http") returns an HTTP instance. For more information about HTTP instances, see https://nodejs.org/api/http.html.

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

Create a server

The createServer () method of the HTTP module accepts a method as a parameter, prototype:

http.createServer([requestListener])

RequestListener is a method that is associated with request events of the http. Server class. In this way, the requestListener will be called when the client requests arrive.

RequestListener has two parameters. The function prototype is as follows:

function (request, response) { }

The type of the first request parameter ishttp.IncomingMessage, ImplementedReadable StreamInterface.
The second parameter type ishttp.ServerResponse, ImplementedWriteable StreamInterface.

The Stream API is here: https://nodejs.org/api/stream.html. At the same time, the request and response are also EventEmitter, which can launch specific events.

The EventEmitter API is here: invoke.

Let's review the code for creating a server:

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

Http. createServer returns an http. Server instance. The listen method of http. Server allows the Server to listen to a port. In this example, It is 8000.

As you can see, we provide an anonymous function to the createServer method. In this method, we wrote "Hello World!" back to the client through the response parameter !" Message.

Analyze client requests

We have analyzed the http. createServer method. Its parameters are a method with two parameters, one representing the request sent by the client and the other representing the response to the client. Let's take a look at the request parameters.

Request ishttp.IncomingMessageThrough this instance, we can get the request parameters, such as the HTTP method, HTTP Version, url, and header. The specific API is here: https://nodejs.org/api/http.html#http_http_incomingmessage.

Let's modify HelloWorld. js (Save As HelloWorld2.js ). The Code is as follows:

// Introduce the http module var http = require ("http"); // create a server and specify the function http to process client requests. 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 and print the HTTP method, version, url, and other information. You can run node HelloWorld2.js to access http: // localhost: 8000 in the browser, and then run to the command line to see what information is output. Here I am like this:

Our simple HelloWorld can send some response data to the client. You can see "Hello World!" in the browser !" . This response is throughhttp.ServerResponseInstanceresponseSent to the client.

http.ServerResponseIt is alsoStream, Or an EventEmitter. The HTTP status code, data, and HTTP header are returned to the customer.

HTTP Module
In the HTTP module of Node. js, the status line is written to the client through the writeHead method of http. ServerResponse. The writeHead method is prototype as follows:

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

The first parameter of this method is statusCode, which is a number such as 200 and 403. The remaining parameters are optional. The last parameter is headers. Here you can use JSON Object Notation to write some HTTP headers, for example:{“Content-Type”:”text/plain”,”Content-Length”:11}. The first optional parameter statusMessage is used to specify a status description message, which can be left blank.

HTTP Header

The header is a key-value pair. For example, the "Content-Type" we see in HelloWorld is a header label that describes the data Type, it may correspond to text files, images, videos, binary files, etc. Similarly, "Content-Length" is used to specify the Data Length. There are many more, such as "Date" and "Connection. For more information, see the previous link.

The header can also use the http. ServerResponseresponse.setHeader(name, value)You can set an HTTP header at a time.

Data

The header is followed by data, and some status codes, such as 200, will be followed by some data. Some, such as 301, 404, 403, and 500, do not have data.

Data is written back to the client through the write method of http. ServerResponse, for example:

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

Here we need to mention that there are two common data transmission encoding methods for HTTP:

Set Content-Length to transmit data with a fixed Length. Set the Transfer-Encoding header to chunked and transmit data in multiple parts.

As in our current HelloWorld example, if the Content-Length header is not set, the HTTP module of Node. js defaultsChunkedEncoding.

We can use Chrome's Developer Tools to view network data clearly. As shown in:

HTTP Response

The three items I marked are the HTTP header information that the HelloWorld sample passes to the browser.

We use the write method of http. ServerResponse to write data to the client. You can write all data at a time, or separate the data for multiple writes. When the amount of data to be transmitted is large, it is reasonable to write data multiple times. For example, if you send a large file to the client, it is more suitable to write data multiple times. You can also use Node. the asynchronous feature of js achieves good performance.

Related Article

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.