search
HomeWeb Front-endJS TutorialTutorial 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 id="nbsp-Not-nbsp-Found">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:

  1. First open `cmd` and enter The directory where the server file is located, such as the `test` directory;

  2. and then enter: `node server debug` (same layer), or `node server `(sub-layer),

  3. will prompt `server running at http://www.php.cn/:8085/`, Indicates that the service is successfully started;

  4. 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;

  1. 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.;

  2. ##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.;

  3. fs, represents the file resource object, specifically you can access the API of the nodejs official website;

  4. path, represents the resource path object, specifically you can access the API of the nodejs official website.

listen indicates the created service listener. Once this port is accessed, it will enter the previous anonymous function callback and return the resource to the client.

For more tutorials on how to build a simple web server using node.js, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
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 Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools