Home  >  Article  >  Web Front-end  >  Tutorial on how to build a simple web server using node.js

Tutorial on how to build a simple web server using node.js

高洛峰
高洛峰Original
2017-02-21 14:39:231530browse

The theme of this article is to use node to build the simplest web server. Later, you can learn more about it according to your needs. Currently, it can be used to simulate simple interactions with the server during the development process, such as returning resource control, etc. Friends who need it can refer to it for reference. Let’s take a look below.

Preface

Using Nodejs to build a Web server is a comprehensive introductory tutorial for learning Node.js, because you need to complete a simple Web server. You need to learn several important modules in Nodejs, such as: http protocol module, file system, url parsing module, path parsing module, and 301 redirection issues. Let's briefly talk about how to build a simple web server.

Earlier if you want to access local resources on the browser side without using a web server, you can use the firefox browser, which can start a small web server by itself.
In order for people who are new to node to understand it generally, I will try to simplify the code in this article as much as possible.

Preparation

First, you need to install nodejs. This can be downloaded from the official website. Currently, I have the v0.12 version installed locally.

After the installation is completed, you can test whether the installation is successful through the command line. Enter: node -v, and the currently installed node version number should be 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 use the following command to install them: npm install xxx.

Start

Next step, create a new js file, which can be 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] || ''; // 命令行第三个参数,用来接收目录,可为空,相对当前server.js文件的目录名称
 // 比如使用命令 node server debug,意思就是debug文件夹与server.js文件同级
 // 且你想以debug文件夹启动web服务

 http.createServer(function (req, res) {
 var pathname = __dirname + url.parse(req.url).pathname;
 dir = dir ? dir : pathname; // 记住dir(目录)
 pathname = dir ? pathname.replace(dir, dir + arg + '/') : pathname; // 替换文件静态路径
 if (path.extname(pathname) == "") {
 pathname += "/";
 }
 if (pathname.charAt(pathname.length - 1) == "/") {
 pathname += "index.html"; // 入口文件,此处默认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可以自己添加信息来简单交互 比如可以修改点header信息 或者修改返回的资源数据
 fs.readFile(pathname, function (err, data) {
 res.end(data);
 });
 }
 else {
 res.writeHead(404, {"Content-Type": "text/html"});
 res.end("<h1>404 Not Found</h1>");
 }
 });
 }).listen(8085, "127.0.0.5"); // 服务器端口

 console.log("server running at http://www.php.cn/:8085/");

Start

After the node installation is completed and the above server.js file is created. 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 first put the current file into the same layer or download it directly, and then enter the following command to start the web service:

  1. First open `cmd` and enter The directory where the server file is located, such as the `test` directory;

  2. and then enter: `node server debug` (same layer), or `node server `(sub-layer),

  3. will prompt `server running at http://www.php.cn/:8085/`, Indicates that the service is successfully started;

  4. Finally open the browser and enter: `127.0.0.5:8085` to access this resource.

Finally

Briefly explain the above code.

First of all, the require at the top indicates which modules need to be used, please quote them first;

arg indicates the third parameter of the input command line, the above is done manually Interception;

createServer method means creating an http service, taking a function as a parameter, and an anonymous function is passed in in the code of this article;

  1. req , represents the http request (request) object, which carries relevant information from the client's http request, such as request method, request query parameters, request header information, etc.;

  2. ##res , represents the http response (return) object, used to return requested resources to the client. You can manually add information, such as returned data, returned header information, etc., returned code, etc.;

  3. fs, represents the file resource object, specifically you can access the API of the nodejs official website;

  4. path, represents the resource path object, specifically you can access the API of the nodejs official website.

listen indicates the created service listener. Once this port is accessed, it will enter the previous anonymous function callback and return the resource to the client.

For more tutorials on how to build a simple web server using node.js, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn