How to build a web server with Node.js
使用nodejs搭建Web服务器是学习Node.js比较全面的入门教程,因为实现Web服务器需要用到几个比较重要的模块:http模块、文件系统、url解析模块、路径解析模块、以及301重定向技术等,下面我们就一起来学习如何搭建一个简单的Web服务器。
相关推荐:《nodejs 教程》
作为一个Web服务器应具备以下几个功能:
- 能显示以 .html/.htm 结尾的 Web 页面
- 能直接打开以 .js/.css/.json/.text 结尾的文件内容
- 显示图片资源
- 自动下载以 .apk/.docx/.zip 结尾的文件
- 形如 http://xxx.com/a/b/ , 则查找b目录下是否有index.html, 如果有就显示,如果没有就列出该目录下的所有文件及文件夹,并可以进一步访问。
- 形如 http://xxx.com/a/b, 则作301重定向到 http://xxx.com/a/b/ , 这样可以解决内部资源引用错位的问题。
引入需要用到的几个模块:
// http协议模块 var http = require('http'); // url解析模块 var url = require('url'); // 文件系统模块 var fs = require('fs'); // 路径解析模块 var path = require('path');
创建服务并在指定的端口监听:
// 创建一个服务 var httpServer = http.createServer(this.processRequest.bind(this)); // 在指定的端口监听服务 httpServer.listen(port, function() { console.log('[HttpServer][Start]', 'runing at http://' + ip + ':' + port + '/'); console.timeEnd('[HttpServer][Start]'); });
在创建服务的时候需要传递一个匿名函数 processRequest 对请求进行处理,processRequest接收两个参数,分别是 request 和 response, request 对象中包含了请求的所有内容,response 是用来设置响应头以及对客户端做出响应操作。
processRequest: function (request, response) { varhasExt = true; varrequestUrl = request.url; varpathName = url.parse(requestUrl).pathname; // 对请求的路径进行解码,防止中文乱码 pathName = decodeURI(pathName); // 如果路径中没有扩展名 if(path.extname(pathName) === '') { // 如果不是以/结尾的,加/并作301重定向 if(pathName.charAt(pathName.length-1) != '/'){ pathName += '/'; varredirect = 'http://'+ request.headers.host + pathName; response.writeHead(301, { location: redirect }); response.end(); return; } // 添加默认的访问页面,但这个页面不一定存在,后面会处理 pathName += 'index.html'; hasExt = false; // 标记默认页面是程序自动添加的 } // 获取资源文件的相对路径 varfilePath = path.join('http/webroot', pathName); // 获取对应文件的文档类型 varcontentType = this.getContentType(filePath); // 如果文件名存在 fs.exists(filePath, function(exists) { if(exists) { response.writeHead(200, {'content-type': contentType}); varstream = fs.createReadStream(filePath, {flags: 'r', encoding: null}); stream.on('error', function () { response.writeHead(500, {'content-type': 'text/html'}); response.end('<h1>500 Server Error</h1>'); }); // 返回文件内容 stream.pipe(response); } else{ // 文件名不存在的情况 if(hasExt) { // 如果这个文件不是程序自动添加的,直接返回404 response.writeHead(404, {'content-type': 'text/html'}); response.end('<h1>404 Not Found</h1>'); } else{ // 如果文件是程序自动添加的且不存在,则表示用户希望访问的是该目录下的文件列表 varhtml = "<head><meta charset='utf-8'></head>"; try{ // 用户访问目录 varfiledir = filePath.substring(0, filePath.lastIndexOf('\\')); // 获取用户访问路径下的文件列表 varfiles = fs.readdirSync(filedir); // 将访问路径下的所以文件一一列举出来,并添加超链接,以便用户进一步访问 for(vari infiles) { varfilename = files[i]; html += "<div><a href='"+ filename + "'>"+ filename + "</a></div>"; } } catch(e){ html += '<h1>您访问的目录不存在</h1>'; } response.writeHead(200, {'content-type': 'text/html'}); response.end(html); } } }); }
请求处理函数中有几个重点需要说一下:
对于路径中有中文的,浏览器会自动进行编码(英文不变,中文会变),因此在接收到地址后,需要对地址进行解码,否则最后得到的路径和真实路径不相符,
当访问路径不是以具体的文件结尾,并且不是以/结尾,则需要通过重定向加上/,表示当前目录,否则当前路径下的静态资源会找不到。
如果访问路径是目录,则列出该目录下所有文件及文件夹,并可以点击访问,为了让中文目录能正常显示,则还要在header中设置charset=utf-8
核心代码就这么多,大概140行左右,完整的代码已上传到 github : https://github.com/git-onepixel/Node,
如果要运行demo,打开 cmd 切换到根目录,运行 node start 即可。
如有问题,欢迎讨论!
更多编程相关知识,请访问:编程教学!!
The above is the detailed content of How to build a web server with Node.js. For more information, please follow other related articles on the PHP Chinese 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











Best Practices: Performance Tuning Guide for Building Web Servers on CentOS Summary: This article aims to provide some performance tuning best practices for users building web servers on CentOS, aiming to improve the performance and response speed of the server. Some key tuning parameters and commonly used optimization methods will be introduced, and some sample codes will be provided to help readers better understand and apply these methods. 1. Turn off unnecessary services. When building a web server on CentOS, some unnecessary services will be started by default, which will occupy system resources.

Permissions and access control strategies that you need to pay attention to before building a web server on CentOS. In the process of building a web server, permissions and access control strategies are very important. Correctly setting permissions and access control policies can protect the security of the server and prevent unauthorized users from accessing sensitive data or improperly operating the server. This article will introduce the permissions and access control strategies that need to be paid attention to when building a web server under the CentOS system, and provide corresponding code examples. User and group management First, we need to create a dedicated

Overview of security auditing and event log management of web servers built on CentOS. With the development of the Internet, security auditing and event log management of web servers have become more and more important. After setting up a web server on the CentOS operating system, we need to pay attention to the security of the server and protect the server from malicious attacks. This article will introduce how to perform security auditing and event log management, and provide relevant code examples. Security audit Security audit refers to comprehensive monitoring and inspection of the security status of the server to promptly discover potential

Entry-level tutorial: A quick guide to building a web server on CentOS Introduction: In today's Internet era, building your own web server has become a need for many people. This article will introduce you to how to build a web server on the CentOS operating system, and provide code examples to help readers quickly implement it. Step 1: Install and configure Apache Open the terminal and install the Apache server through the following command: sudoyuminstallhttpd After the installation is complete, start Apac

Go language has become a popular development language, especially for network programming. When writing a web server in Go, there are many best practices to ensure the security, maintainability and scalability of the server. Here are some suggestions and practices that can help you improve the efficiency and reliability of your Go web server. Using the standard library There are many packages related to network programming in the Go language standard library. For example, the net/http package helps you write HTTP servers, and the net package helps handle low-level network connections.

Best practices and precautions for building web servers under CentOS7 Introduction: In today's Internet era, web servers are one of the core components for building and hosting websites. CentOS7 is a powerful Linux distribution widely used in server environments. This article will explore the best practices and considerations for building a web server on CentOS7, and provide some code examples to help you better understand. 1. Install Apache HTTP server Apache is the most widely used w

Understand the differences and advantages of Gunicorn compared to other web servers Introduction: When building web applications, choosing the right web server is crucial. Gunicorn (GreenUnicorn) is a highly stable and scalable Python web server. This article will introduce the differences and advantages of Gunicorn and other web servers, and provide some specific code examples. 1. Features of Gunicorn Multi-process: Gunicorn supports multi-process mode

NGINXPM2VPS: Building a secure web application server With the development of the Internet, web applications have become more and more important in our lives. In order to ensure the stability and security of our web application, we need a reliable web server. In this article, we will explain how to set up a secure web application server on a VPS using NGINX and PM2. The first step is to choose the right VPS (VirtualPrivateServer)
