A tutorial on the method of building a simple web server with node. js
- 2021-07-22 08:32:35
- OfStack
Preface
Using Nodejs to build Web server is a comprehensive introductory tutorial for learning Node. js, because 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 problem. Let's briefly talk about how to build a simple Web server.
If you want to access local resources on the browser side without using web server earlier, you can use firefox browser, which can start a small web server by itself.
In order to let people who have just come into contact with node can generally understand it, I will try my best to simplify the code in this article.
Prepare
First of all, you need to install nodejs, which can be downloaded from official website. At present, I install v version 0.12 locally.
After the installation is completed, you can test whether the installation is successful through the command line. Type:
node -v
The node version number currently installed should be displayed.
The modules used in this article are all nodejs core modules, which do not need to be downloaded from outside. If necessary, you can use the following command to install:
npm install xxx
.
Begin
In the next step, create a new js file, which can be named server. js with the following code:
var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');
var dir, arg = process.argv[2] || ''; // Command line 3 Parameters, used to receive the directory, can be empty, relative to the current server.js Directory name of file
// For example, using commands node server debug Which means debug Folder and server.js Document peer
// And you want to use debug Folder startup web Services
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"; // Entry file, where the default 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 You can add your own information for simple interaction For example, you can modify the point header Information Or modify the returned resource data
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"); // Server port
console.log("server running at http://127.0.0.5:8085/");
Start
When node is installed and the above server. js file is created. Put it on the same level as the folder you want to visit, or put it directly on the lower level. For example, if you want to access the d:\ test\ debug folder.
You can put the current file in the same layer or directly under it, and then enter the following command to start the web service:
First open ` cmd 'and enter the directory where the server file is located, such as ` test' directory; Then enter: `node server debug
` (on the same floor), or `
node server
` (Sublayer),
You will be prompted with '
server running at http://127.0.0.5:8085/
`, indicating that the service was successfully started;
Finally, open the browser and enter: '127.0. 0.5: 8085' to access this resource.
Finally
Explain the above code briefly.
First of all, the top require indicates that you need to use those modules, and refer to 1 first;
arg indicates the third parameter of the input command line, which is manually intercepted;
createServer method means to create an http service, with functions as parameters, and an anonymous function is passed in this code;
listen indicates the created service listener. Once 1 accesses this port, it will enter the previous anonymous function callback and return the resource to the client.
Summarize