First, installation
First, go to http://nodejs.org to download the installation. My next version is 0.8.14. The installation is simple, the next step is OH. Then configure the installation directory in path, and MSI will install NPM (Node Package Manager) together.
My installation directory is C:\Program Files (x86) \nodejs. At this point, using the cmd Command Window node -v
, the npm -v
command to view the installed version
1.1, HelloWorld
Create a new file in the Node.js Engineering directory hello.js, knocking a line of code inside
Console.log (' Hello, Nodejs. ');
Enter the command line console and enter the Node.js Engineering directory knocking node Hello.js
The console outputs "Hello, Nodejs."
1.2, the web version of the HelloWorld
Create a new http.js in the Node.js Engineering directory with the following code
var http = require ("http");
Http.createserver (function (request, response) {
Response.writehead ({"Content-type": "Text/html"});
Response.Write ("Hello world!");
Response.End ();
}). Listen (8000);
Start the service on the command line, knocking node Http.js
Then open the browser address bar input http://localhost:8000/, see the page output Hello world! was successful.
The Node.js version must be synchronized with the API
Node.js version number is regular, even version is stable version, odd version unstable version
2 HelloWorld Code Analysis
Well, from now on, we'll analyze our HelloWorld by line.
Introducing Modules
var http = require ("http");
The Require method is used to introduce a module whose parameter is the name of the module. For example, the file system module can be introduced like this:
We can use the require () method as a global method, but in fact it is more like a local method belonging to a module, its documentation reference here: https://nodejs.org/api/globals.html.
The Require method returns an instance of a module, such as require ("http"), and returns 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 () that involves our second line of code.
Creating a server
The HTTP module's Createserver () method accepts a method as a parameter, and the prototype is:
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 invoked when the client request arrives.
Requestlistener has two parameters, the function prototype is as follows:
function (Request, response) {}
The first parameter request is the type http.IncomingMessage
that implements the Readable Stream
interface.
The second parameter is the type http.ServerResponse
that implements the Writeable Stream
interface.
The API for the stream is here: https://nodejs.org/api/stream.html. At the same time, request and response or Eventemitter, can launch a specific event.
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.
Again, let's review the code that we created the server:
Http.createserver (
function (request, response) {
Response.writehead ({"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, in the example of 8000.
As you can see, we provide an anonymous function to the Createserver method. In this method, we write "Hello world!" back to the client via the response parameter. News.
Profiling client Requests
Before we analyzed the Http.createserver method, its parameter is a method with two parameters, one represents the client sent over the request, one represents the response to the client. Let's look at the request parameters.
Request is an http.IncomingMessage
example, through this example, we can get requests parameters, such as HTTP method, HTTP version, URL, head, and so on, the specific API here: HTTPS://NODEJS.ORG/API/HTTP.HTML#HTTP_ Http_incomingmessage.
We'll look at it by modifying Helloworld.js (Save as Helloworld2.js). The code is as follows:
Introducing HTTP Module
var http = require ("http");
Create the server to specify functions
http.createserver (function
(request, Response) {
Console.log ("Method-" + Request.method);
Console.log ("version-" + request.httpversion);
Console.log ("url-" + request.url);
Response.writehead ({"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 perform node helloworld2.js, browser access to http://localhost:8000, and then run to the command line to see what information is output, here's what I do:
Our simple HelloWorld already can send some response data to the client, you can see "Hello world!" in the browser Words. This response is sent to the http.ServerResponse
client through an instance of response
.
http.ServerResponse
is also a Stream
, or a eventemitter. We use it to return the HTTP status code, data, HTTP headers, etc. to the customer.
HTTP Module
In the Node.js HTTP module, the status line is written to the client via the Http.serverresponse Writehead method. The Writehead method prototype is as follows:
Response.writehead (statuscode[, statusmessage][, headers])
The first parameter of this method, which is statuscode, is the number 200, 403, and the rest of the 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 that you can not fill out.
HTTP Header
The head is some key-value, for example, we see in the HelloWorld "Content-type", is used to illustrate the data type of the head tag, the corresponding may be text files, pictures, videos, binary, etc. Similarly, "content-length" is used to specify the length of the data. There are many more, such as "Date", "Connection" and so on. Specifically, refer to the previous link bar.
The head can also use HTTP. The Serverresponse response.setHeader(name, value)
method can be set individually, one at a time to set an HTTP header.
Data
After the head is the data, some status code, such as 200, the follow-up will have some data. And some, such as 301, 404, 403, 500, most of which have no data.
Data is passed through HTTP. The Serverresponse write method is written back to the client, such as this:
Response.setheader ("Content-type", "text/html");
Here, there are two common ways to encode HTTP data:
Set Content-length, transmit fixed-length data set transfer-encoding head to chunked, block transfer data
Like our current HelloWorld example, the Content-length header is not set, and the Node.js HTTP module defaults to chunked encoding.
We use the Chrome browser's developer tools to view the network data and we can see it clearly. As shown in the following illustration:
HTTP response
All three of my annotations 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 you want to transfer a large amount of data, it is more reasonable to write several times, such as you send a large file to the client, it is more suitable for multiple writes, you can also take advantage of the asynchronous characteristics of node.js, get good performance.