How to build a simple web server using node. js

Source: Internet
Author: User
Tags small web server node server
The topic of this article is to use node to build the simplest web server. Later, you can learn more about it as needed. Currently, it can be used to simulate simple interaction with the server during the development process, for example, return resource control. If you want to learn more, let's take a look. The topic of this article is to use node to build the simplest web server. Later, you can learn more about it as needed. Currently, it can be used to simulate simple interaction with the server during the development process, for example, return resource control. If you want to learn more, let's take a look.

Preface

Using Nodejs to build a Web server is to learn Node. js is a comprehensive introductory tutorial. To complete a simple Web server, you need to learn several important modules in Nodejs, such: the http protocol module, file system, url parsing module, path parsing module, and 301 redirection problems. Next we will briefly explain how to build a simple Web server.

To access local resources without using a web server earlier, you can use the firefox browser to start a small web server.
I will try to simplify the code in this article to make it understandable to people who are new to node.

Preparation

First, you need to install nodejs. You can download it from the official website. Currently, I have installed v0.12 locally.

After the installation is complete, run the command line to test whether the installation is successful. Enter:node -vThe version number of the currently installed node is displayed.
The modules used in this article are all nodejs core modules and do not need to be downloaded from the outside. If necessary, you can run the following command to install them:npm install xxx.

Start

Next, create a new js file named server. js. The Code is as follows:

Var http = require ('http'); var url = require ('url'); var path = require ('path'); var fs = require ('fs '); var dir, arg = process. argv [2] | ''; // The third parameter of the command line, which is used to receive directories. It can be empty and relative to the current server. directory Name of the js file // For example, the command node server debug means that the debug folder and server. js file at the same level // and you want to start the web Service http in the debug folder. 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 the static path of the file if (path. extname (pathname) = "") {pathname + = "/";} if (pathname. charAt (pathname. length-1) = "/") {pathname + = "index.html"; // enter the file, which contains index.html} fs. exists (pathname, function (exists) {if (exists) {switch (path. extname (pathname) {case ". html ": res. writehead( 200, {"Content-Type": "text/html"}); break; case ". js ": res. writehead( 200, {"Content-Type": "text/javascript"}); break; case ". css ": res. writehead( 200, {"Content-Type": "text/css"}); break; case ". gif ": res. writeHead (200, {"Content-Type": "image/gif"}); break; case ". jpg ": res. writeHead (200, {"Content-Type": "image/jpeg"}); break; case ". png ": res. writehead( 200, {"Content-Type": "image/png"}); break; default: res. writeHead (200, {"Content-Type": "application/octet-stream "});} // res can add information for simple interaction. For example, you can modify the header information or the returned resource data fs. readFile (pathname, function (err, data) {res. end (data) ;}) ;}else {res. writehead( 404, {"Content-Type": "text/html"}); res. end ("404 Not Found ");}});}). listen (8085, "127.0.0.5"); // server port console. log ("server running at #: 8085 /");

Start

After node installation and the preceding server. js file are created. Put it together with the folder you want to access, which can be placed at the same layer or directly at the lower layer. For example, if you want to access the d: \ test \ debug folder.

You can first put the current file at the same layer or directly, and then enter the following command to start the web Service:

  1. Open 'cmd' first and enter the directory where the server File is located, for example, the 'test' directory;

  2. Then enter :'node server debug'(Same layer), or'node server'(Child layer ),

  3. The prompt'server running at #:8085/', Indicating that the service is successfully started;

  4. Finally, open the browser and enter '127. 0.0.5: 123' to access this resource.

Last

Briefly explain the above Code.

First, the above require indicates that the required modules are used. First, reference them;

Arg indicates the third parameter of the input command line, which is intercepted manually;

The createServer method indicates creating an http service with the function as the parameter. An anonymous function is input in the code of this article;

  1. Req indicates the http request object, which carries information about the http request from the client, such as the request method, request query parameters, and request header information;

  2. Res indicates the http response (returned) object, which is used to return request resources to the client. You can manually add information such as returned data, returned header information, and returned code;

  3. Fs, indicating file resource objects. You can access the api on the official node. js website;

  4. Path indicates the resource path object. You can access the api on the official node. js website.

Listen indicates the service listener created. Once this port is accessed, it enters the previous anonymous function callback and returns the resource to the client.

For more information about how to use node. js to build a simple web server, see PHP!

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.