1. Installation
First, go to http://nodejs.org to download and install. The version I'm down is 0.8.14. The installation is very simple, the next step is next. Then configure the installation directory in the path, and msi will install npm (Node Package Manager) together.
My installation directory is C:/Program Files (x86)/nodejs. At this time, use the cmd command window node -v and npm -v command to view the installed version under the npm -v command
1.1. helloworld
Create a new file hello.js in the Node.js project directory and type a line of code in it
console.log('hello, nodejs.') ;Enter the command line console, enter the Node.js project directory and type node hello.js
The console outputs "hello, nodejs."
1.2. Web version of helloworld
Create a new http.js 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 click node http.js
Then open the browser address bar and enter http://localhost:8000/, and see Hello World! output on the page and it succeeds.
The version of node.js must be synchronized with the API
The version number of node.js is regular, even version is stable version, odd version is non-stable version
2 HelloWorld code analysis
OK, start analyzing our HelloWorld line by line from now on.
Introduce modules
var http = require("http");The require method is used to introduce a module, and 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 certain module. Its documentation is here: https://nodejs.org/api/globals.html.
The require method returns an instance of a certain module, such as require("http") returns an HTTP instance. The reference documentation for HTTP instances 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.
Create a server
The createServer() method of the HTTP module accepts a method as a parameter, and the prototype is:
http.createServer([requestListener])
requestListener is a method that will be associated with the request event of the http.Server class. In this way, when the client request arrives, the requestListener will be called.
RequestListener has two parameters, and the function prototype is as follows:
function (request, response) { } The type of the first parameter request is http.IncomingMessage , which implements the Readable Stream interface.
The type of the second parameter is http.ServerResponse , which implements the Writeable Stream interface.
The Stream API is here: https://nodejs.org/api/stream.html. At the same time, request and response are EventEmitters, which can emit specific events.
The EventEmitter API is here: https://nodejs.org/api/events.html#events_class_events_eventemitter. Later we will talk about how to use EventEmitter to launch and process events.
Let's review the code we created the 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 can let the server listen on a certain port, which is 8000 in the example.
As you can see, we provide an anonymous function to createServer method. In this method, we write back the "Hello World!" message to the client through the response parameter.
Analyze client requests
We analyzed the http.createServer method earlier. Its parameters are a method with two parameters. One represents the request sent by the client and the other represents the response to write back to the client. Let's take a look at the request parameters.
request is an instance of http.IncomingMessage . Through this instance, we can get the request parameters, such as HTTP method, HTTP version, url, header, etc. The specific API is here: https://nodejs.org/api/http.html#http_http_incomingmessage.
Let's take a look by modifying HelloWorld.js (save as HelloWorld2.js). The code is as follows:
// Introduce http module var http = require("http"); // Create a server, specifying the function that handles client requests 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 used the console object to output some debugging information and printed HTTP method, version, url and other information. You can execute node HelloWorld2.js, the browser visits http://localhost:8000, and then run to the command line to see what information is output. I'm like this:
Our simple HelloWorld can already send some response data to the client, and you can see the words "Hello World!" in your browser. This response is sent to the client via an instance response of http.ServerResponse .
http.ServerResponse is also a Stream or EventEmitter. Through it, we return HTTP status code, data, HTTP headers and other information to the client.
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 prototype of the writeHead method is 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, where you can use 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 can be not filled in.
HTTP header
The header is some key-value pairs. For example, the "Content-Type" we see in HelloWorld is the header tag used to indicate the data type, which may correspond to text files, pictures, videos, binary, etc. Similarly, "Content-Length" is used to specify the data length. There are many more, such as "Date", "Connection", etc. Please refer to the previous link.
The header can also be set separately using the response.setHeader(name, value) method of http.ServerResponse, and one HTTP header can be set at a time.
data
After the header, there is data. Some status codes, such as 200, will have some data in the future. And some, such as 301, 404, 403, 500, most of them have no data.
The 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 HTTP data transmission encoding methods:
Set Content-Length, transfer fixed-length data, set the Transfer-Encoding header to chunked, transfer data in chunks
Like our current HelloWorld example, without setting the Content-Length header, the HTTP module of Node.js defaults to chunked encoding.
We use Chrome browser's developer tools to view network data, which can be clearly seen. As shown in the figure below:
HTTP response
The three points I marked out are all HTTP header information passed to the browser by the HelloWorld example.
We write data to the client through the write method of http.ServerResponse. You can write all the data at once, or you can write the data separately and multiple times. When the amount of data to be transferred is large, writing in multiple times is a more reasonable approach. For example, if you send a large file to the client, it is more suitable for writing in multiple times. You can also use the asynchronous feature of Node.js to obtain good performance.