English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Preface
Using Nodejs to build a web server is a comprehensive beginner 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, and301Redirection issues, let's briefly explain how to set up a simple web server.
In the past, if you wanted to access local resources on the browser side without using a web server, you could use the Firefox browser, which can start a small web server by itself.
In order to make the code easy to understand for those who are just getting started with node, I will try to simplify the code in this article.
Prepare
First, you need to installnodejs,this can be downloaded from the official website, the current local installation is v0.12version.
After installation, you can test whether the installation is successful through the command line by entering: node -v, should display the current installed node version number.
The modules used in this article are all core modules of nodejs, which do not need to be downloaded from external sources. If necessary, you can use the following command to install: npm install xxx.
Start
Next, create a 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] || ''; // The third parameter of the command line is used to receive the directory, which can be empty, and the name of the directory relative to the server.js file // For example, use the command node server debug, which means the debug folder is at the same level as the server.js file // and you want to start the web service with the debug folder http.createServer(function (req, res) { var pathname = __dirname + url.parse(req.url).pathname; dir = dir ? dir : pathname; // Remember dir(directories) 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"; // Entry file, here index.html is the default } 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 to interact simply, for example, you can modify some 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
After the node installation is complete and the above server.js file is also created, place it together with the folder you want to access, which can be placed at the same level or directly below. For example, if you want to access the d:\test\debug folder.
You can put the current file in the same level or directly below it, and then enter the following command to start the web service:
Finally
A simple explanation of the code above.
First, the most above require indicates which modules need to be used, let's reference them first;
arg indicates the third command line parameter entered, the above is manually intercepted;
The createServer method indicates creating an http service, taking a function as a parameter, an anonymous function is passed in in the code of this article;
listen indicates the service listener created, once accessed, it will enter the anonymous function callback before it, and return the resource to the client.
Summary
That's all for this article. I hope the content of this article can bring some help to everyone's learning or work. If you have any questions, you can leave messages for communication. Thank you for your support of the呐喊 tutorial.
Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report violations, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)