search
HomeWeb Front-endJS TutorialHow to build a web server with Node.js

How to build a web server with Node.js

Jan 05, 2021 pm 05:45 PM
node.jsweb server

使用nodejs搭建Web服务器是学习Node.js比较全面的入门教程,因为实现Web服务器需要用到几个比较重要的模块:http模块、文件系统、url解析模块、路径解析模块、以及301重定向技术等,下面我们就一起来学习如何搭建一个简单的Web服务器。

How to build a web server with Node.js

相关推荐:《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(&#39;<h1 id="nbsp-Server-nbsp-Error">500 Server Error</h1>&#39;);
            });
            // 返回文件内容
            stream.pipe(response);
        } else{ // 文件名不存在的情况
            if(hasExt) {
                // 如果这个文件不是程序自动添加的,直接返回404
                response.writeHead(404, {&#39;content-type&#39;: &#39;text/html&#39;});
                response.end(&#39;<h1 id="nbsp-Not-nbsp-Found">404 Not Found</h1>&#39;);
            } else{
                // 如果文件是程序自动添加的且不存在,则表示用户希望访问的是该目录下的文件列表
                varhtml = "<head><meta charset=&#39;utf-8&#39;></head>";
                try{
                    // 用户访问目录
                    varfiledir = filePath.substring(0, filePath.lastIndexOf(&#39;\\&#39;));
                    // 获取用户访问路径下的文件列表
                    varfiles = fs.readdirSync(filedir);
                    // 将访问路径下的所以文件一一列举出来,并添加超链接,以便用户进一步访问
                    for(vari infiles) {
                        varfilename = files[i];
                        html += "<div><a  href=&#39;"+ filename + "&#39;>"+ filename + "</a></div>";
                    }
                } catch(e){
                    html += &#39;<h1 id="您访问的目录不存在">您访问的目录不存在</h1>&#39;;
                }
                response.writeHead(200, {&#39;content-type&#39;: &#39;text/html&#39;});
                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!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software