Home Web Front-end JS Tutorial How to create Web and TCP servers in Node.js

How to create Web and TCP servers in Node.js

Jun 22, 2018 pm 04:33 PM
node.js tcp server web server

This article mainly introduces the methods and processing skills of using Node.js to create Web servers and TCP servers. Readers who need it can learn it.

Create a Web server using the http module

Function of the Web server:

Accept HTTP requests (GET, POST, DELETE, PUT, PATCH)

Process HTTP requests (handle it yourself, or request other programs to handle it)

Respond (return pages, files, various types of data, etc.)

Common Web server architecture:

Nginx, Apache: responsible for accepting HTTP requests, determining who will handle the request, and returning the results of the request

php-fpm/php module: processing assigned to itself request, and return the processing results to the assignor

Common request types:

Request files: including static files (web pages, pictures, front-end JavaScript files, css files ...), and the files processed by the program

Complete specific operations: such as logging in, obtaining specific data, etc.

Node.js Web server:

Does not rely on other specific web server software (such as Apache, Nginx, IIS...)

Node.js code handles request logic

Node.js The code is responsible for various "configurations" of the Web server

Use Express to create a Web server

Simple Express server

Static file service

Routing

Middleware

Simple Express server:

var express = require('express'); 
var app = express(); 
app.get('', function(req, res){ 
<span style="white-space:pre"> </span>res.end(&#39;hello\n&#39;); 
<span style="white-space:pre"> </span>}); 
<span style="white-space:pre"> </span>app.listen(18001, function afterListen(){ 
<span style="white-space:pre"> </span>console.log(&#39;express running on http://localhost:18001&#39;); 
<span style="white-space:pre"> </span>});
Copy after login

Static file scope:

Web pages, plain text, images, front-end JavaScript code, CSS style sheet files, media files, font files

Use Express to access static files

<span style="white-space:pre"></span>app.use(express.static(&#39;./public&#39;));
Copy after login

Routing:

Assign different requests to the corresponding processing functions

Distinguishing: path, request method

Three routing implementation methods:

path: relatively simple

Router: more suitable for multiple sub-routes under the same route

route: More suitable for API

Middleware

Connect: Node.js middleware framework

Layered processing

Each layer Implement a function

Create TCP server

Use net module to create TCP server

Use telnet to connect to TCP server

Use net to create TCP client

Use node.js to build a simple web server JS code part:

var http = require(&#39;http&#39;);
var url = require(&#39;url&#39;);
var path = require(&#39;path&#39;);
var fs = require(&#39;fs&#39;);
var dir, arg = process.argv[2] || &#39;&#39;; // 命令行第三个参数,用来接收目录,可为空,相对当前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 + &#39;/&#39;) : 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://127.0.0.5:8085/");
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Error in loading path in laydate.js

How to implement route parameter passing in vue-router

How to use jQuery to operate table to merge cells

The above is the detailed content of How to create Web and TCP servers in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Best Practices: Performance Tuning Guide for Building a Web Server on CentOS Best Practices: Performance Tuning Guide for Building a Web Server on CentOS Aug 04, 2023 pm 12:17 PM

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.

Security auditing and event log management of web servers built on CentOS Security auditing and event log management of web servers built on CentOS Aug 05, 2023 pm 02:33 PM

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

Permissions and access control strategies that you need to pay attention to before building a web server on CentOS Permissions and access control strategies that you need to pay attention to before building a web server on CentOS Aug 05, 2023 am 11:13 AM

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

Introductory Tutorial: A quick guide to setting up a web server on CentOS Introductory Tutorial: A quick guide to setting up a web server on CentOS Aug 04, 2023 pm 06:04 PM

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

Best practices for writing web servers in Go Best practices for writing web servers in Go Jun 18, 2023 pm 07:38 PM

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 a web server under CentOS 7 Best practices and precautions for building a web server under CentOS 7 Aug 25, 2023 pm 11:33 PM

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

NGINX PM2 VPS: Building a secure web application server NGINX PM2 VPS: Building a secure web application server Sep 28, 2023 pm 05:34 PM

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)

The reference value of Xiaopi Linux operation and maintenance panel tool to build web server The reference value of Xiaopi Linux operation and maintenance panel tool to build web server Feb 01, 2024 am 10:03 AM

This article will introduce you to the process of building a web server on Linux server. Linux one-click installation of web environment has certain reference value. Linux one-click installation of web environment. I hope it will be helpful to friends who are learning Linux operation and maintenance! sshroot@ip-p222. Then we can use apt and yum commands to update the system sudoaptupdatesudoaptupgradesudoyumupdate3. Next, we need to download the server software linuxweb server. There are two methods. One is to use the package management tool to install it, and the other is to download the source code for compilation and installation. 1. Package management tool installs apache or nginxsudoap

See all articles