How to build a simple Web server using node. JS Tutorial

Source: Internet
Author: User
Tags small web server node server server port

Preface using Nodejs to build a Web server is a comprehensive introductory tutorial for node. js, because to complete a simple Web server, you need to learn some of the more important modules in Nodejs, such as: HTTP protocol module, file system, URL parsing module, path parsing module, and the 301 redirect problem, let's talk a little bit about how to build a simple Web server. If you want to access local resources on the browser without using a Web server earlier, you can use the Firefox browser to start a small Web server yourself. I will try to simplify the code in this article in order to make it easier for people who are just touching node to understand it. Prepare first, need to install NODEJS, this can go to the official website to download, currently I install the v0.12 version locally. After the installation is complete, you can test whether the installation was successful through the command line, enter:, the current installation node version number should be displayed. The modules used in this article are Nodejs core modules that do not need to be downloaded externally and, if necessary, can be installed using the following command:. To start the next step, create a new JS file that can be named Server.js, with the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21st
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
var http = require (' http ');
var url = require (' URL ');
var path = require (' path ');
var fs = require (' FS ');

var dir, arg = process.argv[2] | | ‘‘; command line third parameter, which is used to receive directories, can be empty, relative to the directory name of the current Server.js file
For example, using the command node server debug, which means that the debug folder and the Server.js file peer
And you want to start the Web service in the Debug folder

Http.createserver (function (req, res) {
var pathname = __dirname + url.parse (req.url). Pathname;
dir = dir? Dir:pathname; Remember dir (directory)
pathname = dir? Pathname.replace (dir, dir + arg + '/'): pathname; Replace file static path
if (path.extname (pathname) = = "") {
Pathname + = "/";
}
if (Pathname.charat (pathname.length-1) = = "/") {
Pathname + = "index.html"; Portal file, default index.html here
}

Fs.exists (pathname, function (exists) {
if (exists) {
Switch (path.extname (pathname)) {
Case ". html":
Res.writehead ($, {"Content-type": "Text/html"});
Break
Case ". js":
Res.writehead ($, {"Content-type": "Text/javascript"});
Break
Case ". css":
Res.writehead ($, {"Content-type": "Text/css"});
Break
Case ". gif":
Res.writehead ($, {"Content-type": "Image/gif"});
Break
Case ". jpg":
Res.writehead ($, {"Content-type": "Image/jpeg"});
Break
Case ". png":
Res.writehead ($, {"Content-type": "Image/png"});
Break
Default
Res.writehead ($, {"Content-type": "Application/octet-stream"});
}

Res can add information to a simple interaction such as the ability to modify the header information or to modify the returned resource data.
Fs.readfile (pathname, function (err, data) {
Res.end (data);
});
}
else {
Res.writehead (404, {"Content-type": "Text/html"});
Res.end ("}
});
}). Listen (8085, "127.0.0.5"); Server port

Console.log ("Server running at http://127.0.0.5:8085/");
Start when node installation is complete and the above Server.js file is also new. Put it together with the folder you want to access, either on the same layer or directly below it. For example, if you want to access the D:\test\debug folder. You can start the Web service by putting the current file in the same layer or directly below it, and then entering the following command:
    1. Open ' cmd ' first, enter the directory where the server file is located, such as the ' Test ' directory;
    2. Then enter: ' (same layer), or ' (sub-layer),
    3. This will prompt "', indicating that the service started successfully;
    4. Finally open the browser, enter: ' 127.0.0.5:8085 ', you can access this resource.
Finally, simply explain the code above. First of all, the top require indicates the need to use the modules, the first reference, ARG represents the input command line of the third parameter, the above is done by manual interception; The Createserver method means to create an HTTP service with function as parameter, and an anonymous function is passed in the code of this article;
    1. Req, which represents the HTTP request (Request) object, carries relevant information from the client's HTTP requests, such as Request method, request query parameter, request header information, etc.
    2. Res, which represents the HTTP response (return) object, which is used to return the requested resource to the client, and can be added manually, such as the returned data, the header information returned, the returned code, and so on;
    3. FS, which represents the file resource object, can access the API of Nodejs official website;
    4. Path, which represents the resource path object, which provides access to the API of the NODEJS official website.
Listen represents the created service listener, which, once accessed, enters the previous anonymous function callback and returns the resource to the client. Summary of the above is the entire content of this article, I hope that the content of this article on everyone to learn or work can bring certain help, if there is doubt you can message exchange. Thank you for your support of the Scripting House.

How to build a simple Web server using node. JS Tutorial

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.