Tutorial on how to build a simple web server using node.js
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:
First open `cmd` and enter The directory where the server file is located, such as the `test` directory;
and then enter: `
node server debug
` (same layer), or `node server
`(sub-layer),will prompt `
server running at http://www.php.cn/:8085/
`, Indicates that the service is successfully started;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;
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.;
- ##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.;
- fs, represents the file resource object, specifically you can access the API of the nodejs official website;
- path, represents the resource path object, specifically you can access the API of the nodejs official website.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.
