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('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
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('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://127.0.0.5:8085/");
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!

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.


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

Atom editor mac version download
The most popular open source editor

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version
Visual web development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools
