Node.js creates Web and TCP servers
In this article, we mainly introduce the methods and processing techniques of using Node.js to create web servers and TCP servers. We hope it can help everyone.
Functions of the Web server:
Accept HTTP requests (GET, POST, DELETE, PUT, PATCH)
Processing HTTP request (handle it yourself, or request other programs to handle it)
Response (return pages, files, various data, etc.)
Common Web server architecture:
Nginx, Apache: Responsible for accepting HTTP requests, determining who will handle the request, and returning the result of the request
php-fpm / php Module: Process the requests assigned to itself 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 files processed by the program
Complete specific operations: such as logging in, obtaining specific data, etc.
Node.js Web server:
Does not depend on other specific web server software (such as Apache, Nginx, IIS...)
Node.js code handles the logic of requests
Node.js 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('hello\n'); <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('express running on http://localhost:18001'); <span style="white-space:pre"> </span>});
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('./public'));
Routing:
Assign different requests to the corresponding processing functions
Distinguish: 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 implements a function
Create TCP server
Use net module to create TCP server
Use telnet to connect to the TCP server
Use net to create a TCP client
Use node.js to build a simple Web server JS code part:
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://127.0.0.5:8085/");
The above content is the Node.js method for creating Web and TCP servers. Hope it helps everyone.
Related recommendations:
##Node.js learning TCP/IP data communication
The above is the detailed content of Node.js creates Web and TCP servers. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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)

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

The web is a global wide area network, also known as the World Wide Web, which is an application form of the Internet. The Web is an information system based on hypertext and hypermedia, which allows users to browse and obtain information by jumping between different web pages through hyperlinks. The basis of the Web is the Internet, which uses unified and standardized protocols and languages to enable data exchange and information sharing between different computers.

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit

Implementation steps: 1. Monitor the scroll event of the page; 2. Determine whether the page has scrolled to the bottom; 3. Load the next page of data; 4. Update the page scroll position.

PHP belongs to the backend in web development. PHP is a server-side scripting language, mainly used to process server-side logic and generate dynamic web content. Compared with front-end technology, PHP is more used for back-end operations such as interacting with databases, processing user requests, and generating page content. Next, specific code examples will be used to illustrate the application of PHP in back-end development. First, let's look at a simple PHP code example for connecting to a database and querying data:

Go builds interactive web applications that run in the browser. Steps: Create Go project and main.go file, add HTTP handler to display messages. Add forms using HTML and JavaScript for user input and submission. Add handling of POST requests in your Go application, receive user messages and return responses. Use FetchAPI to send POST requests and handle server responses.

JavaScript and WebSocket: Building an efficient real-time search engine Introduction: With the development of the Internet, users have higher and higher requirements for real-time search engines. When searching with traditional search engines, users need to click the search button to get results. This method cannot meet users' needs for real-time search results. Therefore, using JavaScript and WebSocket technology to implement real-time search engines has become a hot topic. This article will introduce in detail the use of JavaScript
