node. js from beginner to novice-resource not loaded? You need to learn address resolution

Source: Internet
Author: User
Tags response write

node. js is what seems to have not required me more to repeat, non-blocking server language, JS writing backstage code, countless articles have been very good to display the charm and prospects of node. For the installation of node. js, you may wish to refer to the blog Park Nievidong http://www.cnblogs.com/Darren_code/archive/2011/10/31/nodejs.html (node. JS first Experience), this article is a good overview of node. JS (from installation to experience to the module of a primer, personal feeling is a good article), I believe through the East brother of this article you can have a preliminary understanding of node.

Node is a very interesting framework that allows a long-term obsession with front-end development of the siege (forgetting that there is another language called back-end language ...). Can feel comfortable (coding habits are the same), but it will also make a novice feel at a loss (why is it from the introduction to proficiency?) Where is the reference book??? )。 This is a front-end master for one of the bright (perhaps only light-eyed O (╯-╰) o), the novice before a halo (if you want to find more information,please read the source (╯-╰) O) frame. In order to let the same novice and I can more or less touch the road, I defy the rule, to find a way for the novice ~

This article is aimed at beginners, the study is shallow, the code level is limited, this is just a basic entry notes, the Master can smile and then point off ...

First of all I assume that you've installed node (http://nodejs.org/#download, 0.6.14 is already mature), so let's start with an introductory code analysis.

Before analyzing, let's think about how the previous server-side language framework works. First, the user accesses our app through a browser. The server then listens to the port to receive request requests from the network side and handles them accordingly. Finally, the results of the processing are returned to the client.

Well, then we can start. The first is the server, if there is no way to start the server, then everything is idle. We may have used a lot of server-side languages (PHP, JAVA, ASP, etc.), the process of receiving HTTP requests and providing Web pages does not seem to work for us, and Apache and IIS seem to be doing it for us. But in node, this step must be done by yourself. We're not just going to implement an application, but also a server that implements HTTP processing.

It's kind of complicated, but it's not a complicated thing for node. We are going to have an initial study of an HTTP server, but we need to brush up before we learn. A bit of node's module mechanism.

Node takes the module mechanism (and JS almost), through the import of modules we can declare variables and assign the instantiated object of the imported module to the variable and use it. The use of the specific modules and uses, please refer to the API, here do not say ...

OK, let's come back and look at the HTTP server composition. First, we make a request to the HTTP module first:

var http = require ("http");

The Require method in node is used to introduce the various modules, which we can import when we need to use the HTTP module. After import, assign it to an HTTP variable and then manipulate the HTTP variable. Let's use Hello World as an example:

1 Http.createserver (function (request, response) {
2 response.writehead ($, {"Content-type": "Text/plain"});
3 Response.Write ("Hello World");
4 Response.End ();
5}). Listen (12345, "127.0.0.1");

Every time I see Hello World, there is a bit of metamorphosis in my heart ...

Let's recall a moment ago: implementing an HTTP server. In fact, this is very simple, the HTTP module comes with the Createserver method can be completed. The method has only one parameter, the type is a function, and the definition in the interface document is "Always receive request event". The Server.listen method (server is the server just created by Createserver) is (port, [hostname], [callback]), the first is the port number of the listener, the second and third is the optional one, The second is the host name, and the third callback function. This function is called only after the port is bound.

Next is the callback function, the callback function has two parameters, the first is the request sent by the client, and the second is the server-side response. This code makes a simple response operation. First, a response header is written, and the response header parameter includes the status code, reason description, and header content. Status codes are HTTP status codes, such as 200, 404, 500, and so on. Reason description and header content optional, specifically see the network header of the writing, there is not much to say (in fact, I will not ...) )。 The Writehead method must be written before the end method, which is certain ...

Response Write method and JS write the same job, is to write data to the page, although the principle is not the same, but there is no preparation to delve into this part of the source we can ignore ... And finally the end method, which has two optional parameters, data and encoding, respectively. This method is used for all response headers after the output of the response body, the end of the response, and the output of all the response data in the pipeline flow. Simply put, in response to the last thing added, it executes after the response will be executed. If the method has parameters, it is equivalent to calling the Response.Write (data, encoding) method before calling the no-argument end method.

Well, the simplest HTTP server is already working. When a user accesses 127.0.0.1 port 12345, the server will listen to the request for this port and write the header with the simplest HelloWorld on the page, and the user will be given a response in the browser to display the content of the response, that is, HelloWorld. This simplest server has been set up, but we can't just be content with that.

Before continuing the next study, I would like to give all the students who have not used JS or not how to use the general about a perhaps you will be slightly strange parameter transfer method-function pass.

In JS, functions and numbers, strings, etc. are defined by Var, and the parameters that are accepted in the process of parameter passing are also weak types of var. And the function type is also passed as a weak type, and when we pass a function, we get not the return value of the function, but the functions themselves. In other words, this function will become the local variable of the function passed to it at run time (I feel very chaotic ...). )。

Let's recall the example that we used an anonymous function as an argument in the Creatserver method, and now we present this anonymous function:

1 var http = require ("http");
2 var Serverhandel = function (Request, response) {
3 response.writehead ($, {"Content-type": "Text/plain"});
4 Response.Write ("Hello World");
5 Response.End ();
6}
7 function Serverrequest () {

3 ·
Ten exports. Serverrequest = Serverrequest;

Exports is the Module.exports object, which can be given as a global variable in node. That is, it is generally used to define global variables, which are used for variable passing between modules. In this I need to briefly say the JS module mechanism, JS module more with the closure package (I do not know that is not right), and the local variables defined in the closure can not be used in the global expansion, that is, other places to call the module can not be used in a separate use of the local variables. Exports can then load the module into the global variable's chain of action.

Speaking of which, we should understand that we are going to make a module reference. Save this code in Serverrequest.js, then create a index.js file, and then reference the Serverrequest module:

1 var server = require ("./serverrequest");
2 server. Serverrequest ();

So we have a basic small module of the building, but also a preliminary understanding of node's module system. So the next step is to do a very important module of learning, that is, the URL module and the path module.

The role of the URL module is to get the requested URL from the request and process it, which has several common methods:

1 Url.parse (string). Pathname;
2 Url.parse (string). query;

The first method is to get the path name after the domain name of the part of the URL request, and the second method gets the parameters passed to the server through get.

and the path module is to solve the file path problem, we first learn three methods:

1 path.extname (P);
2 Path.join ([path1], [path2], [...]);
3 path.exists (P, [callback]);

The first method is the method that gets the extension, and the parameter is the URL path. The second method is to do the path splicing use, used to standardize the final path, parameters are required to splice the path. The third method is to verify that the path exists or not, the first parameter is a normalized path, and the second is an optional callback function that is called regardless of whether the path exists or not, and the function has a exist parameter that indicates whether the path exists.

Well, now we can build a simple path server with these two modules. With this server, we can deploy local static sites, address the various resources that pages and pages need to load, and finally feed back the requested resources.

1//Request module
2 var http = require (' http ');
3 var url=require (' url ');
4 var fs = require ("FS"); Here first import the file module, just do a simple operation, specific about the file module learning on the subsequent file server will be further learning.
5 var path = require ("path");
6//Create an HTTP server
7 var server=http.createserver (start). Listen (12345);
8//Based on path gets the return content type string for the HTTP return header
9 var getcontenttype=function (FilePath) {
var contenttype= "";
11//Use the path resolution module to get the file name extension
var extension=path.extname (FilePath);
Switch (extension) {
". html":
Contenttype= "text/html";
break;
". js":
Contenttype= "Text/javascript";
break;
Case ". css":
Contenttype= "Text/css";
break;
". gif":
Contenttype= "Image/gif";
break;
". jpg":
Contenttype= "Image/jpeg";
break;
Case ". png":
Contenttype= "Image/png";
break;
". ico":
Contenttype= "Image/icon";
a break;
Default:
Contenttype= "Application/octet-stream";
37}
ContentType return; Returns the content type string
39}
//web Server main function, parse request, return Web content
Funwebsvr var = function (req, res) {
42//Get the requested URL
var Url=req.url;
44//Use URL parsing module to get the path name in the URL
var pathName = Url.parse (requrl). PathName;
if (Path.extname (pathName) = = "") {
47//If path does not have extension
if (pathname.length<2) {//If it is the default domain name
pathname+= "/";
50}
Wuyi else{
pathname+= ". html";
53}
54}
else{
Path.extname (pathName)! = ". html") {
Pathname= "..." + PathName;
58}
59}
if (Pathname.charat (pathname.length-1) = = "/") {
61//If you access the directory
pathname+= "login.html"; Specify as Default Web page
63}
var filePath = PathName;
65//Use Path resolution module to assemble the actual file path
if (Pathname.charat (pathname.length). Search (/./) = = 1) {
FilePath = Libpath.join ("./html", pathName);
68};
69//Determine if the file exists
Libpath.exists (Filepath,function (exists) {
if (exists) {//File exists
72//write the content type in the return header
Res.writehead ($, {"Content-type": Fungetcontenttype (FilePath)});
74//Create read-only stream for return
The var stream = Libfs.createreadstream (FilePath, {flags: "R", Encoding:null});
76//Specify 404 error if stream read error
Stream.on ("Error", function () {
Res.writehead (404);
Res.end ("80});
81//Connect file stream and HTTP return stream for the pipeline to return the actual web content
Stream.pipe (RES);
83}
+ Else {//file does not exist
85//Return 404 error
Res.writehead (404, {"Content-type": "Text/html"});
Res.end ("88}
89});
90}

This is an example of a Daniel's blog, and later found that can only be loaded into a single page, and other resources can not be very good loading, a large correction, mainly added to the different pathname addressing and loading. In this example, the CSS, JS, and image folders are in the same directory as the HTML folder where the page resides.

I believe that through this example, we have been able to simply let a static website on our server support up. The next time we will simply deploy a file system, I hope you can continue to pay attention to. Novice on the road, the article code written are relatively rough, I hope you correct. Bye











Tags: node. js good text to top concern my collection this article key Yao
Follow-27
Followers-35+ + 10 (please comment on the article) «Previous: Canvas elements Easy Tutorial (6) (most of them go from Firefox, they only write simple code analysis)
» Next: Simulation of Google today's baggage to do gadgets posted @ 2012-03-30 17:32 key Yao Read (6008) Comments (14) Edit Collection

node. js from beginner to novice-resource not loaded? You need to learn address resolution

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.