This article is merged according to the order of publication of Xiaomanzs's Nodejs column , with a total of 87 articles.
Nodejs Chapter 1 (Introduction)
Overview
- nodejs is not a
JavaScriptapplication, nor is it a programming language, because the programming language usesJavaScript, and Nodejs is the runtime ofJavaScript.

- Nodejs is built on the V8 engine. The V8 engine is written in C/C++, so our JavaSCript code needs to be converted from C/C++ before execution.
- NodeJs uses asynchronous I/O and event-driven design concepts to efficiently handle a large number of concurrent requests. It provides a non-blocking I/O interface and event loop mechanism, allowing developers to write high-performance, scalable applications. Asynchronous I/O is ultimately implemented by the
libuvevent loop library. - NodeJs uses npm as a package management tool similar to python's pip or java's Maven. Currently, npm has millions of modules. www.npmjs.com/
- Nodejs is suitable for some IO-intensive applications, but is not suitable for CPU-intensive applications. nodejsIO relies on libuv to have strong processing capabilities, and the CPU can easily cause high CPU usage due to the single thread of nodejs. If you must do CPU-intensive applications, you can use C++ plug-ins or
clusterprovided by nodejs. (CPU-intensive refers to image processing or audio processing that requires a large number of data structures + algorithms)
nodeJs rough architecture diagram

Nodejs application scenarios
The following shows that not everything is written in nodejs, but the running environment can cooperate with nodejs or rely on nodejs to run.
Front-end
Vue Angular React nuxtjs nextjs
Backend
serverLess
web application epxress Nestjs koa
RPC service gRPC
Reptile Puppeteer cheerio
BFF layer gateway layer
Immediate application socket.io
Desk front-end
electron
tauri
NWjs
Mobile version
weex
ionic
hybrid
React Native
Infrastructure side
webpack vite rollup gulp
less scss postCss
babel swc
inquire command shelljs
Embedded
Ruff js
Unit testing
jest vitest e2e
CICD
Jenkins docker Husky miniprogram-ci
Reverse proxy
http-proxy Any-proxy
Conclusion
By studying this chapter, you can learn about nodejs's high performance, scalability, simplicity, and some usage scenarios.
Nodejs Chapter 2 (Installation)
Install nodejs
Visit official website

LTS long-term support version
Current early adopter version

Choose your own operating system windows Mac Linux Windows needs to distinguish between 64-bit and 32-bit. Mac needs to distinguish between 64-bit and ARM chips. Linux is the same as above. Among them, msi and pkg can be installed directly, which is relatively simple.
Mac Pkg

windows msi

You can also download the compressed package yourself and configure environment variables
Check if the installation is successful

Nodejs Chapter 3 (Npm Package json)
npm
npm (full name Node Package Manager) is a package management tool for Node.js. It is a command line-based tool that helps developers install, upgrade, remove and manage dependencies in their own projects.
- Tools similar to
PHP:Composer. It is a package manager for PHP that can be used to download, install and manage PHP dependencies, similar to npm. - Tools similar to
Java:Maven. It is a build tool and project management tool for Java that can automate the building, testing and deployment of Java applications, similar to the functions of npm and webpack. - Tools similar to
Python:pip. It is a package manager for Python that can be used to install and manage Python dependencies, similar to npm. - Tools similar to
Rust:Cargo. It is a package manager and build tool for Rust that can be used to download, compile, and manage Rust dependencies, similar to the functions of npm and Maven.
npm command
npm init: Initialize a new npm project and create a package.json file.npm install: Install a package or a group of packages and store a node_modules in the current directory.npm install <package-name>: Install the specified package.npm install <package-name> --save: Install the specified package and add it to the dependency list in the package.json file.npm install <package-name> --save-dev: Install the specified package and add it to the development dependency list in the package.json file.npm install -g <package-name>: Install the specified package globally.npm update <package-name>: Update the specified package.npm uninstall <package-name>: Uninstall the specified package.npm run <script-name>: Execute the script command defined in the package.json file.npm search <keyword>: Search the npm library for packages containing the specified keyword.npm info <package-name>: View detailed information of the specified package.npm list: List all packages installed in the current project.npm outdated: List the packages that need to be updated in the current project.npm audit: Check dependencies in the current project for security vulnerabilities.npm publish: Publish the self-developed package to the npm library.npm login: Log in to your npm account.npm logout: Log out of the current npm account.npm link: Link the local module to the globalnode_modulesdirectorynpm config listis used to list all npm configuration information. Execute this command to view all npm configuration information at the current system and user levels, as well as the configuration information of the current project (if you execute this command in the project directory)npm get registryis used to obtain the value of the registry configuration item in the current npm configuration. The registry configuration item is used to specify the download address of the npm package. If not specified, the official npm package registry address is used by default.npm set registrynpm config set registry <registry-url>command, modify the value of the registry configuration item to the specified<registry-url>address
Package json
Execute npm init to initialize a package.json
name: Project name, must be a unique string, usually a combination of lowercase letters and hyphens.version: Project version number, usually using semantic version number specification.description: Project description.main: The path of the main entry file of the project, usually a JavaScript file.keywords: Keyword list of the project to facilitate others to search and discover the project.author: Information about the project author, including name, email, website, etc.license: The license type of the project, which can be a custom license type or a common open source license (such as MIT, Apache, etc.).dependencies: A list of packages that the project depends on. These packages will be automatically installed when the project is run.devDependencies: A list of packages required during project development. These packages will not be released with the project, but will only be used during development.peerDependencies: The peer dependency of the project, that is, the modules required by the project are dependent on other modules.scripts: Defines some script commands, such as starting projects, running tests, etc.repository: Information about the project code warehouse, including type, URL, etc.bugs: The project’s bug report address.homepage: The official website address or document address of the project.

version The three-segment version number is usually 1.0.0 Major version number Minor version number Revision number, Large version numbers are usually upgraded only when there are major changes. Minor version numbers are usually for upgrades that add functionality. The revision number is usually for bug fixes and upgrades
npm install usually installs modules flatly, but sometimes nesting occurs because of different versions. A depends on C1.0, B depends on C1.0, D depends on C2.0, At this time C 1.0 will be placed in node_moduels of A B, C2.0 will be placed in node_moduels under the D module
Nodejs Chapter 4 (Npm install principle)
What happens when executing npm install?
The dependencies installed first will be stored in node_modules in the root directory. By default, they are installed in a flat manner, and the sorting rule is .bin first, then @ series, and then sorted by the first letter abcd, etc., and the algorithm used is breadth-first traversal. When traversing the dependency tree, npm will first process the dependencies in the root directory of the project, and then process the dependencies of each dependent package layer by layer until all dependencies are processed. When processing each dependency, npm will check whether the version number of the dependency meets the version requirements of other dependencies in the dependency tree. If not, it will try to install a suitable version.

Flat?
Flatness is only the ideal state as follows

When installing a certain second-level module, if a first-level module with the same name and the same version is found, that module will be reused directly
Because the C module under module A is installed to the first level, this allows module B to reuse the C module that is under the same level and has the same name and version.
Under non-ideal conditions

Because the dependent modules required by B and A are different (B requires C of v2.0, and A requires C of v1.0), B cannot reuse the C v1.0 module of A like in 2. Therefore, if module redundancy still occurs in this situation, he will continue to build a layer of node_modules for B, which is non-flattening.
npm install subsequent process

Just look at the picture for the specific process. It’s very detailed.
As for what can be configured in npmrc, I will give you a demo reference.
registry=http://registry.npmjs.org/
# 定义npm的registry,即npm的包下载源
proxy=http://proxy.example.com:8080/
# 定义npm的代理服务器,用于访问网络
https-proxy=http://proxy.example.com:8080/
# 定义npm的https代理服务器,用于访问网络
strict-ssl=true
# 是否在SSL证书验证错误时退出
cafile=/path/to/cafile.pem
# 定义自定义CA证书文件的路径
user-agent=npm/{npm-version} node/{node-version} {platform}
# 自定义请求头中的User-Agent
save=true
# 安装包时是否自动保存到package.json的dependencies中
save-dev=true
# 安装包时是否自动保存到package.json的devDependencies中
save-exact=true
# 安装包时是否精确保存版本号
engine-strict=true
# 是否在安装时检查依赖的node和npm版本是否符合要求
scripts-prepend-node-path=true
# 是否在运行脚本时自动将node的路径添加到PATH环境变量中
The role of package-lock.json
Many friends only know that this thing can lock the version record dependency tree details
- version This parameter specifies the version number of the current package
- resolved This parameter specifies the download address of the current package
- integrity is used to verify the integrity of the package -dev This parameter specifies that the current package is a development dependency package -bin This parameter specifies the path and name of the executable file in the current package
- engines This parameter specifies the Node.js version range that the current package depends on
Here comes the knowledge point, package-lock.json helps us cache. It will generate a unique key through name + version + integrity information. This key can find the cache record under the corresponding index-v5, which is under the npm cache folder.

If a cache record is found, the hash value of the tar package will be found, and the corresponding binary file will be extracted to node_modeules

Nodejs Chapter 5 (Npm run principle)
npm run xxx What happened
Follow the example below to see what happens during the npm run dev example.

Read the script command (dev:vite) corresponding to the scripts of package json. Vite is an executable script. Its search rules are:
- First search for the executable command vite from node_modules/.bin of the current project
- If not found, go to the global node_modules to find the executable command vite
- If you haven't found it yet, search in the environment variables.
- Report an error if it cannot be found again.
If found successfully, you will find three files

Because nodejs is cross-platform, the executable commands are compatible with various platforms
- .sh file is for Linux unix Macos
- .cmd for Windows cmd use
- .ps1 for Windows powerShell use
npm life cycle
I didn’t expect that npm execution commands also have a life cycle! ! !
"predev": "node prev.js",
"dev": "node index.js",
"postdev": "node post.js"
When executing the npm run dev command, predev will be executed automatically. Its life cycle is executed before dev, then executes the dev command, and then executes postdev, that is, executed after dev.
Application scenarios such as npm run build can delete the dist directory after packaging, etc.
post: For example, after you write a tool and publish it to npm, you can write a ci script to help you push it to git, etc.
Who has used vue-cli, for example? github.com/vuejs/vue-c…

Nodejs Chapter 6 (npx)
What is npx
npx is a command line tool, which is a new feature in npm version 5.2.0. It allows users to run packages installed in local projects or in remote repositories without installing global packages.
The function of npx is to run the executable files in the node package on the command line without the need to install these packages globally. This makes it easier for developers to manage package dependencies and avoids global pollution issues. It also helps developers use different versions of packages in their projects without version conflicts.
Advantages of npx
- Avoid global installation:
npxallows you to execute npm packages without requiring you to install it globally first. - Always use the latest version: If you do not install the corresponding npm package locally,
npxwill download and use the latest version from the npm package repository. - Execute any npm package:
npxcan not only execute the commands defined in thescriptspart ofpackage.json, but also execute any npm package. - Execute GitHub gist:
npxcan even execute GitHub gist or other public JavaScript files.
The difference between npm and npx
npx focuses on executing commands and executing a certain module command. Although the module will be installed automatically, the focus is on executing a certain command
npm focuses on installing or uninstalling a certain module. It focuses on installation and does not have the function of executing a certain module.
Example
create-react-app.bootcss.com/docs/gettin…

For example, when creating a react project, it needs to be installed globally.
npm install -g create-react-app
Then execute create-react-app my-app. This will cause two problems.
- First you need to install this package globally to occupy disk space
- And if you need to update, you have to execute the update command
Example 2
npm ls -g 查看全局安装的包

I have not installed vite globally.
Install vite for the current project
npm i vite -D

After the installation was completed, I found that I could not execute the vite command.
At this time you can use npx vite

The running rules of npx are the same as npm. Search the local directory to see if there is .bin. If not, go to the global node_moduels to find it. If it is not there, download the package and run the command, and then delete the package.
Nodejs Chapter 7 (Release npm package)
What are the benefits of publishing npm packages?
- It is convenient for teams or cross-teams to share code. It can be easily managed using npm packages, and version control can also be carried out.
- The necessary technology for making open source wheels. Otherwise, how can the wheel you have made be used by others? Is it a USB disk copy?
- This is the interview question I was asked when I was interviewing Byte
- Increase your personal IP to let more people know about your technical capabilities and contributions
Preparation before publishing
npm adduser
First check if it is an npm source and then create an npm account.

After creation, use npm login to log in to the account

After logging in, use npm publish to publish the npm package

Published successfully. If 403 appears, the package name is occupied.

Nodejs Chapter 8 (npm build private server)
Build npm private server
Are there any benefits from building a private server?
- Can be used offline. You can deploy the npm private server to an intranet cluster so that private packages can be accessed offline.
- Improve package security. Use private npm repositories to better manage your packages and avoid vulnerabilities when using public npm packages.
- Improve the download speed of packages. Using a private npm repository, you can cache frequently used npm packages locally, thereby significantly increasing the download speed of packages and reducing the download time of dependent packages. This is very useful for internal team development and continuous integration, deployment and other scenarios
How to build npm private server
Verdaccio is a tool that can help us quickly build npm private servers
npm install verdaccio -g
Very simple to use
verdaccio can be run directly

Then access the default port 4873

Just switch to simplified Chinese

Basic commands
#创建账号
npm adduser --registry http://localhost:4873/
# 账号 密码 邮箱
# 发布npm
npm publish --registry http://localhost:4873/
#指定开启端口 默认 4873
verdaccio --listen 9999
# 指定安装源
npm install --registry http://localhost:4873
# 从本地仓库删除包
npm unpublish <package-name> --registry http://localhost:4873
Other configuration file items
Nodejs Chapter 9 (Modularization)
Nodejs modular specifications follow two sets, one set of CommonJS specifications and the other set of esm specifications.
CommonJS Specification
The introduced module (require) supports four formats
- Support the introduction of built-in modules such as
httposfschild_processand other nodejs built-in modules - Support the introduction of third-party modules
expressmd5koa, etc. - Support the introduction of self-written modules ./ ../ etc.
- Support the introduction of addon C++ extension module .node file
const fs = require("node:fs") // 导入核心模块
const express = require("express") // 导入 node_modules 目录下的模块
const myModule = require("./myModule.js") // 导入相对路径下的模块
const nodeModule = require("./myModule.node") // 导入扩展模块
Export module exports and module.exports
module.exports = {
hello: function () {
console.log("Hello, world!")
},
}
If you don’t want to export the object, export the value directly
module.exports = 123
ESM module specification
The imported module import must be written in the header
Note that an option must be enabled when using the ESM module Open package.json and set type:module
import fs from "node:fs"
If you want to import a json file, special processing is required. You need to add an assertion and specify the type json. The lower version of node does not support it.
import data from './data.json' assert { type: "json" };
console.log(data);
Load the overall object of the module
import * as all from "xxx.js"
Dynamically import modules
Import static loading does not support doping in logic. If you want to load dynamically, please use the import function mode.
if (true) {
import("./test.js").then()
}
module export
- Exporting a default object default can only have one non-repeatable export default
export default {
name: "test",
}
- Export variables
export const a = 1
The difference between Cjs and ESM
- Cjs is based on synchronous loading at runtime, and esm is based on asynchronous loading at compile time.
- Cjs can modify the value, but the esm value cannot be modified (readable)
- Cjs cannot support tree shaking, but esm supports tree shaking.
- The top-level this in commonjs points to the module itself, while the top-level this in ES6 points to undefined
Nodejs partial source code analysis
How to process .json files
Module._extensions[".json"] = function (module, filename) {
const content = fs.readFileSync(filename, "utf8")
if (policy?.manifest) {
const moduleURL = pathToFileURL(filename)
policy.manifest.assertIntegrity(moduleURL, content)
}
try {
setOwnProperty(module, "exports", JSONParse(stripBOM(content)))
} catch (err) {
err.message = filename + ": " + err.message
throw err
}
}
Use fs to read the json file. After the reading is completed, it is a string, and then JSON.parse turns it into an object and returns it.
How to process .node files
Module._extensions[".node"] = function (module, filename) {
if (policy?.manifest) {
const content = fs.readFileSync(filename)
const moduleURL = pathToFileURL(filename)
policy.manifest.assertIntegrity(moduleURL, content)
}
// Be aware this doesn't use `content`
return process.dlopen(module, path.toNamespacedPath(filename))
}
It was found that the .node file is processed through the process.dlopen method.
How to process .js files
Module._extensions[".js"] = function (module, filename) {
// If already analyzed the source, then it will be cached.
//首先尝试从cjsParseCache中获取已经解析过的模块源代码,如果已经缓存,则直接使用缓存中的源代码
const cached = cjsParseCache.get(module)
let content
if (cached?.source) {
content = cached.source //有缓存就直接用
cached.source = undefined
} else {
content = fs.readFileSync(filename, "utf8") //否则从文件系统读取源代码
}
//是不是.js结尾的文件
if (StringPrototypeEndsWith(filename, ".js")) {
//读取package.json文件
const pkg = readPackageScope(filename)
// Function require shouldn't be used in ES modules.
//如果package.json文件中有type字段,并且type字段的值为module,并且你使用了require
//则抛出一个错误,提示不能在ES模块中使用require函数
if (pkg?.data?.type === "module") {
const parent = moduleParentCache.get(module)
const parentPath = parent?.filename
const packageJsonPath = path.resolve(pkg.path, "package.json")
const usesEsm = hasEsmSyntax(content)
const err = new ERR_REQUIRE_ESM(
filename,
usesEsm,
parentPath,
packageJsonPath
)
// Attempt to reconstruct the parent require frame.
//如果抛出了错误,它还会尝试重构父模块的 require 调用堆栈
//,以提供更详细的错误信息。它会读取父模块的源代码,并根据错误的行号和列号,
//在源代码中找到相应位置的代码行,并将其作为错误信息的一部分展示出来。
if (Module._cache[parentPath]) {
let parentSource
try {
parentSource = fs.readFileSync(parentPath, "utf8")
} catch {
// Continue regardless of error.
}
if (parentSource) {
const errLine = StringPrototypeSplit(
StringPrototypeSlice(
err.stack,
StringPrototypeIndexOf(err.stack, " at ")
),
"\n",
1
)[0]
const { 1: line, 2: col } =
RegExpPrototypeExec(/(\d+):(\d+)\)/, errLine) || []
if (line && col) {
const srcLine = StringPrototypeSplit(parentSource, "\n")[line - 1]
const frame = `${parentPath}:${line}\n${srcLine}\n${StringPrototypeRepeat(
" ",
col - 1
)}^\n`
setArrowMessage(err, frame)
}
}
}
throw err
}
}
module._compile(content, filename)
}
If the module has been cached, read it directly from the cache. If there is no cache, read the file from fs, and determine if it is cjs but the type is module, report an error, and read the detailed line number from the parent module to report an error. If there is no problem, call compile
Module.prototype._compile = function (content, filename) {
let moduleURL
let redirects
const manifest = policy?.manifest
if (manifest) {
moduleURL = pathToFileURL(filename)
//函数将模块文件名转换为URL格式
redirects = manifest.getDependencyMapper(moduleURL)
//redirects是一个URL映射表,用于处理模块依赖关系
manifest.assertIntegrity(moduleURL, content)
//manifest则是一个安全策略对象,用于检测模块的完整性和安全性
}
/**
* @filename {string} 文件名
* @content {string} 文件内容
*/
const compiledWrapper = wrapSafe(filename, content, this)
let inspectorWrapper = null
if (getOptionValue("--inspect-brk") && process._eval == null) {
if (!resolvedArgv) {
// We enter the repl if we're not given a filename argument.
if (process.argv[1]) {
try {
resolvedArgv = Module._resolveFilename(process.argv[1], null, false)
} catch {
// We only expect this codepath to be reached in the case of a
// preloaded module (it will fail earlier with the main entry)
assert(ArrayIsArray(getOptionValue("--require")))
}
} else {
resolvedArgv = "repl"
}
}
// Set breakpoint on module start
if (resolvedArgv && !hasPausedEntry && filename === resolvedArgv) {
hasPausedEntry = true
inspectorWrapper = internalBinding("inspector").callAndPauseOnStart
}
}
const dirname = path.dirname(filename)
const require = makeRequireFunction(this, redirects)
let result
const exports = this.exports
const thisValue = exports
const module = this
if (requireDepth === 0) statCache = new SafeMap()
if (inspectorWrapper) {
result = inspectorWrapper(
compiledWrapper,
thisValue,
exports,
require,
module,
filename,
dirname
)
} else {
result = ReflectApply(compiledWrapper, thisValue, [
exports,
require,
module,
filename,
dirname,
])
}
hasLoadedAnyUserCJSModule = true
if (requireDepth === 0) statCache = null
return result
}
First, it checks whether the security policy object policy.manifest exists. If it exists, it means there are security policy restrictions that need to be processed.
The function converts the module file name into URL format. Redirects is a URL mapping table used to handle module dependencies. Manifest is a security policy object used to detect the integrity and security of the module, and then call wrapSafe
function wrapSafe(filename, content, cjsModuleInstance) {
if (patched) {
const wrapper = Module.wrap(content);
//支持esm的模块
//import { a } from './a.js'; 类似于eval
//import()函数模式动态加载模块
const script = new Script(wrapper, {
filename,
lineOffset: 0,
importModuleDynamically: async (specifier, _, importAssertions) => {
const loader = asyncESM.esmLoader;
return loader.import(specifier, normalizeReferrerURL(filename),
importAssertions);
},
});
// Cache the source map for the module if present.
if (script.sourceMapURL) {
maybeCacheSourceMap(filename, content, this, false, undefined, script.sourceMapURL);
}
//返回一个可执行的全局上下文函数
return script.runInThisContext({
displayErrors: true,
});
}
wrapSafe calls the wrap method
let wrap = function (script) {
return Module.wrapper[0] + script + Module.wrapper[1]
}
//(function (exports, require, module, __filename, __dirname) {
//const xm = 18
//\n});
const wrapper = [
"(function (exports, require, module, __filename, __dirname) { ",
"\n})",
]
The wrap method is found to wrap our code into a function
//(function (exports, require, module, __filename, __dirname) {
//const xm = 18 our code
//\n});
Then continue to look at the wrapSafe function, and find that the returned string, which is the code after packaging, is put into the script in the nodejs virtual machine, to see if there is dynamic import to load, and finally returns the result after execution. Then continue to look at _compile, get the function returned by wrapSafe, and call it through Reflect.apply because five parameters [exports, require, module, filename, dirname] need to be filled in, and finally return the execution result.
Nodejs Chapter 10 (Global Variables)
How to define global variables in nodejs?
Use global to define global variables in nodejs. The defined variables can also be accessed in the imported file, such as a.js global.xxx = 'xxx' require('xxx.js') xxx.js. This variable can also be accessed. In the browser, the global variables we define are all in window, and nodejs is in global. Different environments need to be judged, so in ECMAScript In 2020, a globalThis global variable appeared. It will automatically switch to global in the nodejs environment. It is very convenient to automatically switch the window in the browser environment.
About other global APIs
Since there is no DOM and BOM in nodejs, in addition to these APIs, other ECMAscript APIs can basically be used.
For example
setTimeout setInterval Promise Math console Date fetch(node v18) 等...
These APIs can be used normally
nodejs built-in global API
dirname filename can only use cjsm to regulate the absence of these two global variables
__dirname
It indicates the absolute path of the current module Contents
__filename
It represents the absolute path of the current module Documentation, including the file name and file extension
require module
The introduction of modules and module exports have been discussed in detail in the previous chapter.
process
process.argv: This is an array containing command line parameters. The first element is the execution path of Node.js, the second element is the path of the currently executed JavaScript file, and the following elements are the command line parameters passed to the script.process.env: This is an object containing the current environment variables. You can access and manipulate environment variables throughprocess.env.process.cwd(): This method returns the path of the current working directory.process.on(event, listener): used to register event listeners. You can useprocess.onto listen for events such asexit,uncaughtException, etc., and execute the corresponding callback function when the event occurs.process.exit([code]): used to exit the current Node.js process. You can provide an optional exit code as a parameter.process.pid: This attribute returns the PID (process ID) of the current process.
These are just some of the common properties and methods of the process object. There are many other properties and methods that can be used to monitor processes, set up signal handling, send IPC messages, etc.
It should be noted that the process object is a global object and can be accessed directly in any module without importing or defining it.
Buffer
- Create
Bufferinstance:
Buffer.alloc(size[, fill[, encoding]]): Creates a newBufferinstance of the specified size with initial content of zero. Thefillparameter can be used to fill the buffer, and theencodingparameter specifies the character encoding for filling.Buffer.from(array): Creates an instance ofBuffercontaining the given array.Buffer.from(string[, encoding]): Creates an instance ofBuffercontaining the given string.
- Read and write data:
buffer[index]: Read or write specific bytes in theBufferinstance by index.buffer.length: Get the byte length of theBufferinstance.buffer.toString([encoding[, start[, end]]]): ConvertBufferinstance to string.
- Convert data:
buffer.toJSON(): ConvertBufferinstance to JSON object.buffer.slice([start[, end]]): Returns a newBufferinstance containing part of the originalBufferinstance.
- Other methods:
Buffer.isBuffer(obj): Checks whether an object is aBufferinstance.Buffer.concat(list[, totalLength]): Concatenate a set ofBufferinstances or byte arrays to form a newBufferinstance.
Please note that starting from Node.js version 6.0, the use of the Buffer constructor has been deprecated. It is recommended to use Buffer.alloc(), Buffer.from() and other methods to create Buffer instances.
The Buffer class is very useful in operations such as handling files, network communications, encryption and decryption, especially when you need to handle binary data
Nodejs Chapter 11 (CSR SSR SEO)
Overview
In the previous chapter, we said that DOM and BOM cannot be operated in the node environment, but if you have to operate DOM and BOM, it is also possible. We need to use a third-party library to help us jsdom
npm i jsdom
jsdom is a library that simulates a browser environment and can use the DOM API in Node.js
Simple case
const fs = require("node:fs")
const { JSDOM } = require("jsdom")
const dom = new JSDOM(`<!DOCTYPE html><div id='app'></div>`)
const document = dom.window.document
const window = dom.window
fetch("https://api.thecatapi.com/v1/images/search?limit=10&page=1")
.then((res) => res.json())
.then((data) => {
const app = document.getElementById("app")
data.forEach((item) => {
const img = document.createElement("img")
img.src = item.url
img.style.width = "200px"
img.style.height = "200px"
app.appendChild(img)
})
fs.writeFileSync("./index.html", dom.serialize())
})
After running the script, an html file will be generated in the execution directory, and the content will be rendered.

CSR SSR
Our above operations belong to SSR (Server-Side Rendering) server-side rendering. Request data and assembly are completed on the server side. Our Vue, react and other frameworks are not discussed here (nuxtjs, nextjs). The rendering splicing is completed on the client side and belongs to CSR(Client-Side Rendering) client-side rendering.
The difference between CSR and SSR
- Page loading method:
- CSR: In CSR, the server returns an initial HTML page, and then the browser downloads and executes the JavaScript file. JavaScript is responsible for dynamically generating and updating the page content. This means that when the initial page loads, there is less content and there may be some delay in page structure and styling.
- SSR: In SSR, the server will pre-generate a complete HTML page on the server side, including the initial page content, before returning it to the browser. The browser receives the HTML page that has already been rendered, so the initial loading speed is faster.
- Content generation and rendering:
- CSR: In CSR, the content generation and rendering of the page is the responsibility of the client-side JavaScript script. When the data changes, JavaScript will regenerate and update the DOM to achieve dynamic changes in content. This approach makes front-end development more flexible and can create complex interactions and animation effects.
- SSR: In SSR, the server executes the application's code when rendering the page and generates the final HTML page. This means that the initial content of the page is generated by the server, which can provide better first-time load performance for some static or less changing content.
- User interaction and experience:
- CSR: In CSR, once the initial page is loaded, subsequent user interaction is usually data exchange with the server through AJAX or WebSocket, and then updating the page content through JavaScript. This approach can provide faster page switching and response times, but may require some additional processing for search engine crawlers and SEO (search engine optimization).
- SSR: In SSR, since the initial content of the page is generated by the server, user interaction can be performed directly on the server and the server returns the updated page. This provides better first load performance and search engine friendly content.
SEO
SEO (Search Engineering Optimization, search engine optimization)
CSR apps are not very SEO friendly
Because less HTML information is obtained when loading for the first time, search engine crawlers may not be able to obtain the complete page content.

But SSR is different. Since SSR pre-generates a complete HTML page on the server side, search engine crawlers can directly obtain the complete page content. This helps search engines correctly understand and evaluate the content of the page

Having said so much, which websites are suitable for CSR and which websites are suitable for SSR?
CSR applications such as ToB backend management system and large-screen visualization can all use CSR rendering without high SEO support.
SSR applications such as content-intensive applications are mostly ToC news websites, blog websites, e-commerce, and portal websites that require higher SEO support.
Nodejs Chapter 12 (path)
The path module is different in different operating systems (windows | posix)
You must be familiar with windows, but you may not have heard of posix.
posix(Portable Operating System Interface of UNIX)
posix stands for Portable Operating System Interface, which means it defines a set of standards. Operating systems that comply with this set of standards include (unix, like unix, linux, macOs, windows wsl), why should we define this set of standards? For example, starting a process in the Linux system requires calling the fork function, and starting a process in Windows requires calling the creatprocess function. This will cause problems. For example, I wrote the code in Linux and need to transplant it to Windows and find that the functions are not unified. The emergence of the POSIX standard is to solve this problem.
Windows does not fully adhere to the POSIX standard. Windows is designed to represent paths differently than POSIX.
On Windows systems, paths use backslashes (\) as path separators. This is different from the forward slash (/) used by POSIX systems. This is due to the history of Windows systems, where earlier Windows operating systems made different design choices.
windows posix difference
The path.basename() method returns the last part of the given path
Handling windows paths in posix
path.basename("C:\temp\myfile.html")
// 返回: 'C:\temp\myfile.html'
The result returned is incorrect. Myfile.html should be returned.
If you want to process the windows path in a posix system and need to call the method of the corresponding operating system, you should modify it to
path.win32.basename("C:\temp\myfile.html")
Return to myfile.html
path.dirname
This API and basename complement each other exactly
path.dirname("/aaaa/bbbb/cccc/index.html")
dirname API returns /aaaa/bbbb/cccc other than the last path.
basename API returns the last path index.html
path.extname
This API is used to return the extension, for example /bbb/ccc/file.txt. The returned value is .txt.
path.extname("/aaaa/bbbb/cccc/index.html.ccc.ddd.aaa")
//.aaa
If there are multiple ., return the last one. If there is no extension, return empty.
path.join
This API is mainly used to splice paths
path.join("/foo", "/cxk", "/ikun")
// /foo/cxk/ikun
Can support .. ./ ../operators
path.join("/foo", "/cxk", "/ikun", "../")
// /foo/cxk/
path.resolve
Used to parse relative paths and return Absolute Path
If multiple absolute paths are passed in, it will return the rightmost absolute path
path.resolve("/aaa", "/bbb", "/ccc")
// /ccc
Pass in absolute path + relative path
path.resolve(__dirname, "./index.js")
// /User/xiaoman/DeskTop/node/index.js
If only relative paths are passed in
path.resolve("./index.js")
// 返回工作目录 + index.js
path.parse path.format
path.format and path.parse complement each other exactly
parse
Used to parse file paths. It accepts a path string as input and returns an object containing the components of the path
path.parse('/home/user/dir/file.txt')
{
root: '/',
dir: '/home/user/dir',
base: 'file.txt',
ext: '.txt',
name: 'file'
}
root: The root directory of the path, which is/.dir: The directory where the file is located, namely/home/user/documents.base: file name, i.e.file.txt.ext: The file extension is.txt.name: Remove the extension from the file name, that is,file.
format is just the opposite, converting the object back to a string
path.format({
root: "/",
dir: "/home/user/documents",
base: "file.txt",
ext: ".txt",
name: "file",
})
// /home/user/dir/file.txt
Nodejs Chapter 13 (os)
Nodejs os module can interact with the operating system
var os = require("node:os")
| Serial number | API | Function |
|---|---|---|
| 1 | os.type() | It returns 'Linux' on Linux, 'Darwin' on macOS, and 'Windows_NT' on Windows |
| 2 | os.platform() | Returns a string identifying the operating system platform for which the Node.js binary was compiled. This value is set at compile time. Possible values are 'aix', 'darwin', 'freebsd', 'linux', 'openbsd', 'sunos', and 'win32' |
| 3 | os.release() | Returns the version of the operating system, such as 10.xxxx win10 |
| 4 | os.homedir() | Return to the user directory. For example, c:\user\xiaoman. The principle is windows echo %USERPROFILE% posix $HOME |
| 5 | os.arch() | Returns the CPU architecture. Possible values are 'arm', 'arm64', 'ia32', 'mips', 'mipsel', 'ppc', 'ppc64', 's390', 's390x', and 'x64' |
Get the CPU thread and detailed information
const os = require("node:os")
os.cpus()
;[
{
model: "Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz",
speed: 2926,
times: {
user: 252020,
nice: 0,
sys: 30340,
idle: 1070356870,
irq: 0,
},
},
{
model: "Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz",
speed: 2926,
times: {
user: 306960,
nice: 0,
sys: 26980,
idle: 1071569080,
irq: 0,
},
},
{
model: "Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz",
speed: 2926,
times: {
user: 248450,
nice: 0,
sys: 21750,
idle: 1070919370,
irq: 0,
},
},
{
model: "Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz",
speed: 2926,
times: {
user: 256880,
nice: 0,
sys: 19430,
idle: 1070905480,
irq: 20,
},
},
]
//.........
-
model: Indicates the model information of the CPU, where "Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz" is a specific model description. -
speed: Indicates the clock speed of the CPU in MHz or GHz. In this case, the speed is 2926 MHz or 2.926 GHz. -
times: is an object containing CPU usage time, which contains the following properties: -
user: Indicates the time (in milliseconds) that the CPU is used by the user program. -
nice: Indicates the time (in milliseconds) that the CPU is used by user programs with lower priority. -
sys: Indicates the time the CPU is used by the system kernel (in milliseconds). -
idle: Indicates the time the CPU has been idle (in milliseconds). -
irq: Indicates the time (in milliseconds) that the CPU is used by the hardware interrupt handler.
For example, if my computer has six cores and twelve threads, it will get 12 threads.

Get network information
const os = require("node:os")
os.networkInterfaces()
{
lo: [
{
address: '127.0.0.1',
netmask: '255.0.0.0',
family: 'IPv4',
mac: '00:00:00:00:00:00',
internal: true,
cidr: '127.0.0.1/8'
},
{
address: '::1',
netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
family: 'IPv6',
mac: '00:00:00:00:00:00',
scopeid: 0,
internal: true,
cidr: '::1/128'
}
],
eth0: [
{
address: '192.168.1.108',
netmask: '255.255.255.0',
family: 'IPv4',
mac: '01:02:03:0a:0b:0c',
internal: false,
cidr: '192.168.1.108/24'
},
{
address: 'fe80::a00:27ff:fe4e:66a1',
netmask: 'ffff:ffff:ffff:ffff::',
family: 'IPv6',
mac: '01:02:03:0a:0b:0c',
scopeid: 1,
internal: false,
cidr: 'fe80::a00:27ff:fe4e:66a1/64'
}
]
}
address: Indicates the IP address of the local loopback interface, here it is'127.0.0.1'.netmask: Indicates the subnet mask of the local loopback interface, here it is'255.0.0.0'.family: represents address family, here is'IPv4', represents IPv4 address.mac: Indicates the MAC address of the local loopback interface, here it is'00:00:00:00:00:00'. Note that there is usually no hardware involved with local loopback interfaces, so the MAC address is usually all zeros.internal: Indicates whether the local loopback interface is an internal interface. Here it istrue, indicating that it is an internal interface.cidr: represents the CIDR notation of the local loopback interface, which is the combination of the network address and the subnet mask. Here it is'127.0.0.1/8', which represents the entire127.0.0.0network.
Case
What's the use of knowing this information?
A very classic example, webpack vite, everyone should have used it. They have a configuration item that can open the browser open:true. Let’s simply copy it.
const { exec } = require("child_process")
const os = require("os")
function openBrowser(url) {
if (os.platform() === "darwin") {
// macOS
exec(`open ${url}`) //执行shell脚本
} else if (os.platform() === "win32") {
// Windows
exec(`start ${url}`) //执行shell脚本
} else {
// Linux, Unix-like
exec(`xdg-open ${url}`) //执行shell脚本
}
}
// Example usage
openBrowser("https://www.juejin.cn")
Nodejs Chapter 14 (process)
process is the API for Nodejs to operate and control the current process, and is a global API mounted under globalThis
API introduction
1. process.arch
Return to the operating system CPU architecture, which is the same as the os.arch we talked about before.
'arm', 'arm64', 'ia32', 'mips', 'mipsel', 'ppc', 'ppc64', 's390', 's390x', and 'x64'
2. process.cwd()
Returns the current working directory. For example, a script executed in F:\project\node> returns this directory. It can also be spliced with path instead of __dirname.

3. process.argv
Get the parameters behind the execution process. The return is an array. This will be useful when we talk about command line interactive tools later. Various cli scaffolding also uses this method to accept configuration parameters, such as webpack.

4. process.memoryUsage
Used to obtain the memory usage of the current process. This method returns an object that contains various memory usage indicators, such as rss (Resident Set Size, resident set size), heapTotal (total heap area size), heapUsed (used heap size) and external (external memory usage), etc.
{
rss: 30932992, // 常驻集大小 这是进程当前占用的物理内存量,不包括共享内存和页面缓存。它反映了进程实际占用的物理内存大小
heapTotal: 6438912, //堆区总大小 这是 V8 引擎为 JavaScript 对象分配的内存量。它包括了已用和未用的堆内存
heapUsed: 5678624, //已用堆大小
external: 423221, //外部内存使用量 这部分内存不是由 Node.js 进程直接分配的,而是由其他 C/C++ 对象或系统分配的
arrayBuffers: 17606 //是用于处理二进制数据的对象类型,它使用了 JavaScript 中的 ArrayBuffer 接口。这个属性显示了当前进程中 ArrayBuffers 的数量
}
5. process.exit()
Calling process.exit() will force the process to exit as soon as possible, even if there are still incompletely completed asynchronous operations pending
Example 5 below will not be printed because it was exited in 2 seconds.

6. process.kill
Similar to exit, kill is used to kill a process. It accepts a parameter and the process ID can be obtained through process.pid.
process.kill(process.pid)
7. process.env
Used to read all environment variables of the operating system, and can also modify and query environment variables.
Modification Note that the modification does not really affect the operating system variables, but only takes effect in the current thread and is released when the thread ends.

Environment variable scenario
Distinguish between development environment and production environment
npm install cross-env
What this library does cross-env is to set and use environment variables across platforms, whether on Windows or POSIX systems. At the same time, it provides a script for setting environment variables, so that you can set the environment variables in the Unix mode in the script, and then it can also run compatible on Windows.
usage
cross-env NODE_ENV=dev

His principle is that if it is windows, call SET. If it is posix, call export to set environment variables.
set NODE_ENV=production #windows
export NODE_ENV=production #posix
Nodejs Chapter 15 (child_process)
child_process child process
Subprocess is the core API of Nodejs. If you know shell commands, it will be very helpful, or if you like to write front-end engineering tools, it is also very useful, and it can handle CPU-intensive applications.
Create child process
Nodejs creates a child process with a total of Seven.API Sync synchronization API. If not added, it is an asynchronous API.
- spawn execution command
- exec execute command
- execFile executes an executable file
- fork creates node child process
execSyncexecution command synchronous executionexecFileSyncexecutes the executable file synchronouslyspawnSyncexecution command synchronous execution
usage
- exec
child_process.exec(command, [options], callback)
Get nodejs version number
exec("node -v", (err, stdout, stderr) => {
if (err) {
return err
}
console.log(stdout.toString())
})
options configuration items
cwd <string> 子进程的当前工作目录。
env <Object> 环境变量键值对。
encoding <string> 默认为 'utf8'。
shell <string> 用于执行命令的 shell。 在 UNIX 上默认为 '/bin/sh',在 Windows 上默认为 process.env.ComSpec。 详见 Shell Requirements 与 Default Windows Shell。
timeout <number> 默认为 0。
maxBuffer <number> stdout 或 stderr 允许的最大字节数。 默认为 200*1024。 如果超过限制,则子进程会被终止。 查看警告: maxBuffer and Unicode。
killSignal <string> | <integer> 默认为 'SIGTERM'。
uid <number> 设置该进程的用户标识。(详见 setuid(2))
gid <number> 设置该进程的组标识。(详见 setgid(2))
- execSync
Get the node version number. If you want to execute a single shell command, execSync is more convenient. Options are the same as above.
const nodeVersion = execSync("node -v")
console.log(nodeVersion.toString("utf-8"))
Open Google Chrome and use exec to open some software such as wx, Google, qq music, etc. The following will open Baidu and enter No trace mode
execSync("start chrome http://www.baidu.com --incognito")
- execFile
execFile is suitable for executing executable files, such as executing a node script or shell file. Windows can write cmd scripts, and posix can write sh scripts.
Simple example
bat.cmd
Create a folder mkdir, enter the directory, write a file test.js and finally execute
echo '开始'
mkdir test
cd ./test
echo console.log("test1232131") >test.js
echo '结束'
node test.js
Use execFile to execute this
execFile(path.resolve(process.cwd(), "./bat.cmd"), null, (err, stdout) => {
console.log(stdout.toString())
})

- spawn
spawn is used to execute some information obtained in real time because spawn returns while executing the stream, and exec returns a complete buffer. The size of the buffer is 200k. If it exceeds, an error will be reported, and spawn has no upper limit.
After spawn is executed, it will throw a close event listener and return a status code. Through the status code, you can know whether the child process is executed successfully. exec can only identify the completion status through the returned buffer, which is more troublesome to identify.
// 命令 参数 options配置
const { stdout } = spawn("netstat", ["-an"], {})
//返回的数据用data事件接受
stdout.on("data", (steram) => {
console.log(steram.toString())
})

exec -> execFile -> spawn
Exec is the bottom through execFile and execFile through spawn.
- fork
The scenario is suitable for a large amount of calculations, or some code that easily blocks the operation of the main process, so it is suitable for developing fork
index.js
const { fork } = require("child_process")
const testProcess = fork("./test.js")
testProcess.send("我是主进程")
testProcess.on("message", (data) => {
console.log("我是主进程接受消息111:", data)
})
test.js
process.on("message", (data) => {
console.log("子进程接受消息:", data)
})
process.send("我是子进程")
send sends information, message receives messages, and can send and receive messages to each other.
The bottom layer of fork uses IPC channel for communication.

Nodejs Chapter 16 (ffmpeg)
FFmpeg is an open source cross-platform multimedia processing tool that can be used to process audio, video and multimedia streams. It provides a set of powerful command line tools and libraries for video transcoding, video editing, audio extraction, audio and video merging, streaming media transmission and other operations.
Main functions and features of FFmpeg:
- Format conversion: FFmpeg can convert a media file from one format to another, supporting almost all common audio and video formats, including MP4, AVI, MKV, MOV, FLV, MP3, AAC, etc.
- Video processing: FFmpeg can perform video encoding, decoding, cropping, rotating, scaling, adjusting frame rate, adding watermarks, etc. You can use it to adjust the resolution of the video, cut and splice video clips, and apply various effects to the video.
- Audio processing: FFmpeg can perform audio encoding, decoding, editing, mixing, volume adjustment and other operations. You can use it to extract audio tracks, cut and splice audio clips, and perform noise reduction, equalizer, and other processing on audio.
- Streaming media transmission: FFmpeg supports real-time transmission of audio and video streams to the network, and can be used in application scenarios such as real-time streaming services, live broadcasts, and video conferencing.
- High video processing efficiency: FFmpeg is an efficient tool that is optimized for processing large video files and high-resolution videos, providing fast processing speeds while maintaining good quality.
- Cross-platform support: FFmpeg can run on multiple operating systems, including Windows, MacOS, Linux, etc., and supports multiple hardware acceleration technologies, such as NVIDIA CUDA and Intel Quick Sync Video.
Installation

Just select the corresponding operating system to download. After the download is completed, configure the environment variables and it will be ok.
Enter ffmpeg -version without reporting an error

Subprocess cooperates with ffmpeg
- Simple demo video to gif
-irepresents the meaning of input
const { execSync } = require("child_process")
execSync(`ffmpeg -i test.mp4 test.gif`, { stdio: "inherit" })

- Add watermark
-vf is video filter
drawtext adds text fontsize size xy vertical and horizontal direction fontcolor color text watermark copy Lower All
const { execSync } = require("child_process")
execSync(
`ffmpeg -i test.mp4 -vf drawtext=text="XMZS":fontsize=30:fontcolor=white:x=10:y=10 test2.mp4`,
{ stdio: "inherit" }
)

- Video cropping + size control
-ss starting time
-to end event
ss written in front of -i may cause accuracy problems, because the video jumps to the relevant position before it is parsed, but the parsing speed is fast
If ss is written after -i, the accuracy will be fine, but the parsing speed will be slower.
const { execSync } = require("child_process")
execSync(`ffmpeg -ss 10 -to 20 -i test.mp4 test3.mp4`, { stdio: "inherit" })
- Extract audio from video
const { execSync } = require("child_process")
execSync(`ffmpeg -i test.mp4 test.mp3`, { stdio: "inherit" })

- Remove watermark
w h width and height xy vertical horizontal coordinate Filter parameters used by delogo to remove watermarks
const { execSync } = require("child_process")
execSync(`ffmpeg -i test2.mp4 -vf delogo=w=120:h=30:x=10:y=10 test3.mp4`, {
stdio: "inherit",
})

Nodejs Chapter 17 (events)
EventEmitter
The core API of Node.js adopts an asynchronous event-driven architecture. Simply put, it uses effective methods to monitor changes in event status and take corresponding actions when the changes occur.
fs.mkdir("/tmp/a/apple", { recursive: true }, (err) => {
if (err) throw err
})
process.on("xxx", () => {})
For example, if you go to a restaurant to eat, the restaurant is a Movement Control Centre, and then you order food, you can understand that an event emit is registered, and then we wait for the waiter to call our number, and when the waiter calls us, we go to pick up the meal. This is monitoring the event on
Event Model
Nodejs event model adopts, Launch Subscription Design Mode

When a publisher has new news, it publishes the news to the dispatch center. The dispatch center will notify all subscribers of this message. This achieves decoupling between publishers and subscribers. Publishers and subscribers no longer directly depend on each other, and they can extend themselves independently.
Code example
const EventEmitter = require("events")
const event = new EventEmitter()
//监听test
event.on("test", (data) => {
console.log(data)
})
event.emit("test", "xmxmxmxmx") //派发事件
The default number of listening messages is 10
const EventEmitter = require("events")
const event = new EventEmitter()
event.on("test", (data) => {
console.log(data)
})
event.on("test", (data) => {
console.log(data)
})
event.on("test", (data) => {
console.log(data)
})
event.on("test", (data) => {
console.log(data)
})
event.on("test", (data) => {
console.log(data)
})
event.on("test", (data) => {
console.log(data)
})
event.on("test", (data) => {
console.log(data)
})
event.on("test", (data) => {
console.log(data)
})
event.on("test", (data) => {
console.log(data)
})
event.on("test", (data) => {
console.log(data)
})
event.on("test", (data) => {
console.log(data)
})
event.on("test", (data) => {
console.log(data)
})
event.emit("test", "xmxmxmxmx")
How to lift the limit: call setMaxListeners and pass in the number
event.setMaxListeners(20)
I only want to monitor once. Even if emit is dispatched multiple times, it will only be triggered once.
const EventEmitter = require("events")
const event = new EventEmitter()
event.setMaxListeners(20)
event.once("test", (data) => {
console.log(data)
})
event.emit("test", "xmxmxmxmx1")
event.emit("test", "xmxmxmxmx2")
How to cancel listening off
const EventEmitter = require("events")
const event = new EventEmitter()
const fn = (msg) => {
console.log(msg)
}
event.on("test", fn)
event.off("test", fn)
event.emit("test", "xmxmxmxmx1")
event.emit("test", "xmxmxmxmx2")
Has anyone used it?
process

Open the nodejs source code and search for the function setupProcessObject

- It first introduces the event module
- Get the prototype object of process
- Set the prototype object of evnet to the prototype object of process
- And rebind the context
- Mount the process to globalThis so we can access this API globally
Nodejs Chapter 18 (util)
Util is a lot of practical or tool-type APIs provided internally by Node.js to facilitate our rapid development.
Since there are many APIs, we introduce some commonly used APIs.
util.promisify
We have mentioned before that most APIs of Node.js are written following the callback function pattern.
For example, the exec we talked about before
Get Node version
import { exec } from "node:child_process"
exec("node -v", (err, stdout) => {
if (err) {
return err
}
console.log(stdout)
})
The above is the conventional writing method
We use util's promisify and change it to promise style. Promiseify accepts a function body original.
import { exec } from "node:child_process"
import util from "node:util"
const execPromise = util.promisify(exec)
execPromise("node -v")
.then((res) => {
console.log(res, "res")
})
.catch((err) => {
console.log(err, "err")
})
Analyze how promiseify is implemented
- The first step of Promiseify is to return a new function
const promiseify = () => {
return () => {}
}
- promiseify accepts a function, and only accepts real parameters in the returned function, and then returns a promise
const promiseify = (original) => {
return (...args) => {
return new Promise((resolve, reject) => {})
}
}
- Call the real function and pass the parameters to original. If it fails, reject. If successful, return resolve. If there are multiple functions, return an object.
const promiseify = (original) => {
return (...args) => {
return new Promise((resolve, reject) => {
original(...args, (err, ...values) => {
if (err) {
return reject(err)
}
if (values && values.length > 1) {
let obj = {}
console.log(values)
for (let key in values) {
obj[key] = values[key]
}
resolve(obj)
} else {
resolve(values[0])
}
})
})
}
}
This can be roughly achieved, but the key of values cannot be obtained because nodejs is not open to us internally. This Symbol kCustomPromisifyArgsSymbol
So the output result is { '0': 'v18.16.0\n', '1': '' }. Normally it should be { stdout: 'v18.16.0\n', stderr: '' }.
But we can’t get the key, so we can only roughly implement it.
util.callbackify
This API is just the opposite, turning the promise type API into a callback function.
import util from "node:util"
const fn = (type) => {
if (type == 1) {
return Promise.resolve("test")
}
return Promise.reject("error")
}
const callback = util.callbackify(fn)
callback(1222, (err, val) => {
console.log(err, val)
})
Analyzing callbackify
const callbackify = (fn) => {
return (...args) => {
let callback = args.pop()
fn(...args)
.then((res) => {
callback(null, res)
})
.catch((err) => {
callback(err)
})
}
}
This is relatively simple, because multiple parameters are considered, but the callback function must be at the last one, so use pop to take it out.
util.format
%s:Stringwill be used to convert all values exceptBigInt,Objectand-0. TheBigIntvalue will be represented byn, and objects without a user-definedtoStringfunction are checked usingutil.inspect()with option{ depth: 0, colors: false, compact: 3 }.%d:Numberwill be used to convert all values exceptBigIntandSymbol.%i:parseInt(value, 10)for all values exceptBigIntandSymbol.%f:parseFloat(value)for all values exceptSymbol.%j: JSON. If the argument contains a circular reference, it is replaced by the string'[Circular]'.%o:Object. A string representation of an object in universal JavaScript object format. Similar toutil.inspect()with option{ showHidden: true, showProxy: true }. This will display the complete object, including non-enumerable properties and proxies.%O:Object. A string representation of an object in universal JavaScript object format. Similar toutil.inspect()without options. This will display the complete object, excluding non-enumerable properties and proxies.%c:CSS. This specifier is ignored and any incoming CSS will be skipped.%%: Single percent sign ('%'). This does not consume parameters.
The syntax is the same as printf in C language
util.format(format, [args])
Example format a string
util.format("%s-----%s %s/%s", "foo", "bar", "xm", "zs")
//foo-----bar xm/zs 可以返回指定的格式
If no formatting parameters are passed in, separate them by spaces.
util.format(1, 2, 3)
//1 2 3
Nodejs Chapter 19 (pngquant)
What is pngquant?
pngquant is a tool for compressing PNG image files. It can significantly reduce the size of PNG files while maintaining image quality and transparency. By reducing file size, web pages load faster and save storage space. pngquant provides a command line interface and libraries that can be easily integrated into a variety of applications and scripts.
What is the principle?
pngquant uses a modified Median Cut quantization algorithm along with other techniques to compress PNG images. Here's how it works:
- First, pngquant builds a histogram to count the color distribution in the image.
- Next, it selects boxes to represent a set of colors. Unlike traditional Median Cut algorithms, pngquant selects boxes that minimize the difference between the colors in the box and the median.
- pngquant uses a perceptual model to give less weight to noisier areas in the image to build a more accurate histogram.
- To further improve the color, pngquant uses a process similar to gradient descent to adjust the histogram. It repeats the Median Cut algorithm multiple times and adds weight to less frequently occurring colors.
- Finally, to generate the optimal palette, pngquant corrects the colors using Voronoi iteration (K-means) to ensure local optima.
- When remapping colors, pngquant only applies error diffusion in areas where multiple adjacent pixels are quantized to the same color and are not edges. This avoids adding noise in areas where visual quality is higher and dithering is not needed.
Through these steps, pngquant is able to reduce the file size of PNG images to a minimum while maintaining image quality.
Median Cut quantization algorithm
Suppose we have a color image of 8x8 pixels, each pixel consists of red, green and blue channels, and the value of each channel ranges from 0 to 255.
- Initialization: We treat each pixel in the image as a color point and put them into an initial color bucket.
- Select the partition bucket: Select a color channel with the largest range in the initial color bucket, assuming we select the red channel.
- Divide colors: For the selected red channel, sort the colors in the color bucket according to the value of the red channel, and find the color value in the middle as the dividing point. Let's say the red value of the dividing point is 120.
Color bucket before division:
- Color 1: (100, 50, 200)
- Color 2: (150, 30, 100)
- Color 3: (80, 120, 50)
- Color 4: (200, 180, 160)
Color bucket after division:
-
Sub-bucket 1:
-
Color 1: (100, 50, 200)
-
Color 3: (80, 120, 50)
-
Sub-bucket 2:
-
Color 2: (150, 30, 100)
-
Color 4: (200, 180, 160)
- Repeat the division: We continue to select the channel with the largest color range, assuming we select the green channel in sub-bucket 1.
Color bucket before division (sub-bucket 1):
- Color 1: (100, 50, 200)
- Color 3: (80, 120, 50)
The divided color bucket (sub-bucket 1):
-
Subbucket 1.1:
-
Color 3: (80, 120, 50)
-
Subbucket 1.2:
-
Color 1: (100, 50, 200)
There are only two colors in sub-bucket 2 and no further division is needed. 5. Color mapping: Map each pixel color in the original image to the color in the closest color bucket.
Suppose a pixel in the original image is (110, 70, 180) and we map it to color 1: (100, 50, 200)
The approximate formula is sqrt((110-100)^2 + (70-50)^2 + (180-200)^2) ≈ 31.62
Through the Median Cut algorithm, we reduce the number of colors in the original image from 64 (8x8 pixels) to 4 color buckets, thus achieving quantization of the image
Call pngquant in Nodejs
We can still use the exec command to call
import { exec } from "child_process"
exec("pngquant 73kb.png --output test.png")
73kb after compression 22kb
import { exec } from "child_process"
exec("pngquant 73kb.png --quality=82 --output test.png")
Quality means the bigger the 0-100, the better.
import { exec } from "child_process"
exec("pngquant 73kb.png --speed=1 --quality=82 --output test.png")
--speed=1: The slowest speed, producing the highest quality output image.--speed=10: Fastest speed, but may result in slightly lower output image quality.
Nodejs Chapter 20 (fs on)
Overview
In Node.js, the fs module is the abbreviation of File System module, which provides various functions for interacting with the file system. Through the fs module, you can perform operations such as reading files, writing files, changing file permissions, creating directories, etc., Node.js is one of the core API.
fs multiple strategies
import fs from "node:fs"
import fs2 from "node:fs/promises"
//读取文件
fs2.readFile("./index.txt").then((result) => {
console.log(result.toString())
})
fs.readFile("./index.txt", (err, data) => {
if (err) {
return err
}
console.log(data.toString())
})
let txt = fs.readFileSync("./index.txt")
console.log(txt.toString())
- fs supports both synchronous and asynchronous modes. With the addition of
Syncfs, the code will be run in a synchronous manner, which will block the following code. Without Sync, the asynchronous mode will not block. - fs has a new promise version. You only need to add /promise after the imported package, and fs can support promise callbacks.
- fs returns a buffer binary data. Every two hexadecimal digits represent one byte.
<Buffer 31 e3 80 81 e9 82 a3 e4 b8 80 e5 b9 b4 e5 86 b3 e8 b5 9b ef bc 8c e6 98 af 53 53 47 e5 af b9 e6 88 98 53 4b 54 ef bc 8c e6 9c 80 e7 bb 88 e6 af 94 e5 ... 635 more bytes>
Commonly used API introduction
Read the file readFile. The first parameter is the path to be read. The second parameter is a configuration item.
encoding supports various encodings such as utf-8
There are a lot of flags
'a': Open the file for appending. If the file does not exist, the file is created.'ax': Similar to'a'but fails if the path exists.'a+': Open the file for reading and appending. If the file does not exist, the file is created.'ax+': Similar to'a+'but fails if the path exists.'as': Open the file in synchronous mode for appending. If the file does not exist, the file is created.'as+': Open the file in synchronous mode for reading and appending. If the file does not exist, the file is created.'r': Open the file for reading. If the file does not exist, an exception occurs.'r+': Open the file for reading and writing. If the file does not exist, an exception occurs.'rs+': Open the file in synchronous mode for reading and writing. Instructs the operating system to bypass the local file system cache.
This is primarily useful for opening files on NFS mounts, as it allows skipping potentially stale local caches. It has a very real impact on I/O performance, so using this flag is not recommended unless needed.
This does not turn fs.open() or fsPromises.open() into a synchronous blocking call. If you need synchronous operation, you should use something like fs.openSync().
'w': Open file for writing. Create (if it does not exist) or truncate (if it exists) the file.'wx': Similar to'w'but fails if the path exists.'w+': Open the file for reading and writing. Create (if it does not exist) or truncate (if it exists) the file.'wx+': Similar to'w+'but fails if the path exists.
import fs2 from "node:fs/promises"
fs2
.readFile("./index.txt", {
encoding: "utf8",
flag: "",
})
.then((result) => {
console.log(result.toString())
})
Read using a readable stream. The usage scenario is suitable for reading Big document
const readStream = fs.createReadStream("./index.txt", {
encoding: "utf8",
})
readStream.on("data", (chunk) => {
console.log(chunk)
})
readStream.on("end", () => {
console.log("close")
})
Create folders. If recursive is turned on, multiple folders can be created recursively.
fs.mkdir("path/test/ccc", { recursive: true }, (err) => {})
Delete folders. If recursive is turned on, all folders will be deleted recursively.
fs.rm("path", { recursive: true }, (err) => {})
Rename the file. The first parameter is the original name. The second parameter is the new name.
fs.renameSync("./test.txt", "./test2.txt")
Monitor file changes and return the monitored events such as change, and the monitored content filename
fs.watch("./test2.txt", (event, filename) => {
console.log(event, filename)
})
Source code analysis
The source code of fs is an encapsulation of the uv_fs_t class of C++ layer through the FSReqCallback class of libuv. In fact, it is to transparently transmit the parameters of our fs to the libuv layer.

mkdir example
// 创建目录的异步操作函数,通过uv_fs_mkdir函数调用
// 参数:
// - loop: 事件循环对象,用于处理异步操作
// - req: 文件系统请求对象,用于保存操作的状态和结果
// - path: 要创建的目录的路径
// - mode: 目录的权限模式 777 421
// - cb: 操作完成后的回调函数
int uv_fs_mkdir(uv_loop_t* loop,
uv_fs_t* req,
const char* path,
int mode,
uv_fs_cb cb) {
INIT(MKDIR);
PATH;
req->mode = mode;
if (cb != NULL)
if (uv__iou_fs_mkdir(loop, req))
return 0;
POST;
}
Notes
const fs = require("node:fs")
fs.readFile(
"./index.txt",
{
encoding: "utf-8",
flag: "r",
},
(err, dataStr) => {
if (err) throw err
console.log("fs")
}
)
setImmediate(() => {
console.log("setImmediate")
})
Why use setImmediate first instead of fs?
Node.js uses libuv for scheduling when reading files.
And setImmediate is scheduled by V8
After the file reading is completed, libuv will push the fs result into the V8 queue.
Nodejs Chapter 20 (fs next)
Overview
In Node.js, the fs module is the abbreviation of File System module, which provides various functions for interacting with the file system. Through the fs module, you can perform operations such as reading files, writing files, changing file permissions, creating directories, etc., Node.js is one of the core API.
API
Write content
const fs = require("node:fs")
fs.writeFileSync("index.txt", "java之父\n余胜军")
- The file written by the first parameter
- The content written in the second parameter
- The third option is the options encoding mode permission flag
'a': Open the file for appending. If the file does not exist, the file is created.'ax': Similar to'a'but fails if the path exists.'a+': Open the file for reading and appending. If the file does not exist, the file is created.'ax+': Similar to'a+'but fails if the path exists.'as': Open the file in synchronous mode for appending. If the file does not exist, the file is created.'as+': Open the file in synchronous mode for reading and appending. If the file does not exist, the file is created.'r': Open the file for reading. If the file does not exist, an exception occurs.'r+': Open the file for reading and writing. If the file does not exist, an exception occurs.'rs+': Open the file in synchronous mode for reading and writing. Instructs the operating system to bypass the local file system cache.
This is primarily useful for opening files on NFS mounts, as it allows skipping potentially stale local caches. It has a very real impact on I/O performance, so using this flag is not recommended unless needed.
This does not turn fs.open() or fsPromises.open() into a synchronous blocking call. If you need synchronous operation, you should use something like fs.openSync().
'w': Open file for writing. Create (if it does not exist) or truncate (if it exists) the file.'wx': Similar to'w'but fails if the path exists.'w+': Open the file for reading and writing. Create (if it does not exist) or truncate (if it exists) the file.'wx+': Similar to'w+'but fails if the path exists.
Additional content
The first way is to set the flag to a and you can also follow the content.
fs.writeFileSync("index.txt", "\nvue之父\n鱿鱼须", {
flag: "a",
})
java之父
余胜军
vue之父
鱿鱼须
Second way
const fs = require("node:fs")
fs.appendFileSync("index.txt", "\nunshift创始人\n麒麟哥")
You can also add content using appendFileSync
Writable stream
const fs = require("node:fs")
let verse = [
"待到秋来九月八",
"我花开后百花杀",
"冲天香阵透长安",
"满城尽带黄金甲",
]
let writeStream = fs.createWriteStream("index.txt")
verse.forEach((item) => {
writeStream.write(item + "\n")
})
writeStream.end()
writeStream.on("finish", () => {
console.log("写入完成")
})
We can create a writable stream, open a channel, and write data all the time to handle a large amount of data writing. After the writing is completed, call end to close the writable stream and listen to the finish event. The writing is completed.
Hard links and soft links
fs.linkSync("./index.txt", "./index2.txt") //硬链接
fs.symlinkSync("./index.txt", "./index3.txt", "file") //软连接
The functions and uses of hard links are as follows:
- File sharing: Hard links allow multiple file names to point to the same file, so that different file names can be used in different locations to reference the same content. Sharing files like this saves storage space, and modifications to the file in multiple locations are reflected on all referenced files.
- File backup: By creating a hard link, you can create a backup of your files without copying them. If the original file changes, the backup file is automatically updated. This saves disk space and ensures that the backup files stay in sync with the original files.
- File renaming: By creating a hard link, you can create a new file name for a file without copying or moving the file. This is useful for scenarios where you need to change the file name but keep the same content and attributes.
Some characteristics and uses of soft links are as follows:
- Soft links can create references to files or directories. This allows you to reference files without copying or moving them, and access the same content in different locations using different file names.
- Soft links can be used to create shortcuts or aliases, allowing you to access complex or deep directory structures through a short or easy-to-remember path.
- Soft links can be used to solve the problem of location changes of files or directories. If the target file or directory is moved or renamed, you only need to update the target path of the soft link without modifying other code that references the file or directory.
Nodejs Chapter 21 (crypto)
The purpose of the crypto module is to provide a generic Encryption and Hash algorithm. It's not impossible to implement these functions with pure JavaScript code, but it will be very slow. After nodejs implements these algorithms in C/C++, it is exposed as a JavaScript interface through the crypto module, which makes it easy to use and runs fast.
Cryptography is an important field in computer science that involves techniques such as encryption, decryption, hash functions, and digital signatures. Node.js is a popular server-side JavaScript runtime environment that provides powerful cryptography modules, allowing developers to easily implement various cryptography functions in their applications. This article will introduce the basic concepts of cryptography and explore commonly used cryptography APIs in Node.js.
Symmetric encryption
const crypto = require("node:crypto")
// 生成一个随机的 16 字节的初始化向量 (IV)
const iv = Buffer.from(crypto.randomBytes(16))
// 生成一个随机的 32 字节的密钥
const key = crypto.randomBytes(32)
// 创建加密实例,使用 AES-256-CBC 算法,提供密钥和初始化向量
const cipher = crypto.createCipheriv("aes-256-cbc", key, iv)
// 对输入数据进行加密,并输出加密结果的十六进制表示
cipher.update("小满zs", "utf-8", "hex")
const result = cipher.final("hex")
// 解密
const de = crypto.createDecipheriv("aes-256-cbc", key, iv)
de.update(result, "hex")
const decrypted = de.final("utf-8")
console.log("Decrypted:", decrypted)
Symmetric encryption is a simple and fast encryption method that uses the same key (called a symmetric key) for encryption and decryption. This means that both the sender and receiver use the same key during encryption and decryption. The encryption speed of the symmetric encryption algorithm is very fast and is suitable for encrypting and decrypting large amounts of data. However, the security of symmetric keys is a challenge because both the sender and the receiver need to ensure that the key is shared securely, otherwise there is a risk that an unauthorized person can obtain the key and decrypt the data.
Asymmetric encryption
const crypto = require("node:crypto")
// 生成 RSA 密钥对
const { privateKey, publicKey } = crypto.generateKeyPairSync("rsa", {
modulusLength: 2048,
})
// 要加密的数据
const text = "小满zs"
// 使用公钥进行加密
const encrypted = crypto.publicEncrypt(publicKey, Buffer.from(text, "utf-8"))
// 使用私钥进行解密
const decrypted = crypto.privateDecrypt(privateKey, encrypted)
console.log(decrypted.toString())
Asymmetric encryption uses a pair of keys, a public key and a private key. The sender uses the recipient's public key to encrypt, and the recipient uses his or her private key to decrypt. The public key can be freely shared with anyone, while the private key must be kept secret. Asymmetric encryption algorithms provide greater security because even if the public key is compromised, only the recipient holding the private key can decrypt the data. However, the encryption speed of asymmetric encryption algorithms is relatively slow and is not suitable for encrypting large amounts of data. Therefore, in practical applications, asymmetric encryption is usually used to exchange symmetric keys, and then a symmetric encryption algorithm is used to encrypt the actual data.
Hash function
const crypto = require("node:crypto")
// 要计算哈希的数据
let text = "123456"
// 创建哈希对象,并使用 MD5 算法
const hash = crypto.createHash("md5")
// 更新哈希对象的数据
hash.update(text)
// 计算哈希值,并以十六进制字符串形式输出
const hashValue = hash.digest("hex")
console.log("Text:", text)
console.log("Hash:", hashValue)
Hash functions have the following characteristics:
- Fixed length output: Regardless of the size of the input data, the output length of the hash function is fixed. For example, common hash functions such as MD5 and SHA-256 generate hash values that are 128 and 256 bits in length respectively.
- Irreversibility: The hash function is one-way, which means that it is very difficult and almost impossible to deduce the original input data from the hash value. Even if the input data changes slightly, its hash value will be completely different.
- Uniqueness: The hash function should have a low collision probability, that is, the possibility of different input data generating the same hash value should be very small. This helps ensure that the hash value uniquely identifies the input data.
Usage scenarios
- We can avoid clear text transmission of passwords by using md5 encryption or sha256
- Verify the file integrity and read the file content to generate md5. If the md5 uploaded by the front end matches the md5 inside the read file by the back end, the file is complete.
Nodejs Chapter 22 (Scaffolding)
Write your own scaffolding
So what is scaffolding?
For example: vue-cli Angular CLI Create React App
Writing your own scaffolding refers to creating a customized tool that can quickly generate the infrastructure and code files of the project, as well as provide some commonly used commands and functions. By writing your own scaffolding, you can define the project's directory structure, file templates, manage project dependencies, generate code snippets, and provide command line interfaces and other functions
- Project structure: Scaffolding defines the directory structure of the project, including source code, configuration files, static resources, etc.
- File templates: Scaffolding provides some predefined file templates, such as HTML templates, style sheets, configuration files, etc., to speed up developers' creation of new files.
- Command line interface: Scaffolding usually provides a command line interface. By entering commands and parameters, developers can perform various tasks, such as creating new projects, generating code files, running tests, etc.
- Dependency management: Scaffolding can help developers manage project dependencies and automatically install and configure required libraries and tools.
- Code generation: Scaffolding can generate common code structures, such as components, modules, routing, etc., to improve development efficiency.
- Configuration management: Scaffolding can provide some default configuration options and allow developers to customize configurations as needed.

Tool introduction
Which front-end doesn’t want to have its own set of scaffolding? In this chapter you will learn a lot of third-party libraries, such as
commander
Commander is an npm library for building command line tools. It provides a simple and intuitive way to create command line interfaces and handle command line parameters and options. Using Commander, you can easily define commands, subcommands, options, and help messages. It can also handle command line interactions, allowing users to interact with your command line tools
inquirer
Inquirer is a powerful command line interactive tool for interacting with users and collecting information. It provides a variety of rich interactive prompts (such as input boxes, selection lists, confirmation boxes, etc.) to help you build a flexible command line interface. With Inquirer, you can ask questions to users, get their input, and take appropriate actions based on their answers.
ora
Ora is an npm library for displaying loading animations in the command line interface. It helps you provide a friendly loading status prompt when performing time-consuming tasks. Ora provides a series of customized loading animations, such as spinners, progress bars, etc. You can choose the appropriate loading animation effect according to your needs, and display the corresponding loading status during task execution.
download-git-repo
Download-git-repo is an npm library for downloading Git repositories. It provides a simple interface to easily download project code from remote Git repositories. You can specify the repository and target directory to download, and optionally specify a branch or tag. Download-git-repo supports downloading code from various Git hosting platforms such as GitHub, GitLab, Bitbucket, etc.
Write code
- index.js
#!/usr/bin/env node
import { program } from "commander"
import inquirer from "inquirer"
import fs from "node:fs"
import { checkPath, downloadTemp } from "./utils.js"
let json = fs.readFileSync("./package.json", "utf-8")
json = JSON.parse(json)
program.version(json.version) //创建版本号
//添加create 命令 和 别名crt 以及描述 以及 执行完成之后的动作
program
.command("create <project>")
.alias("ctr")
.description("create a new project")
.action((project) => {
//命令行交互工具
inquirer
.prompt([
{
type: "input",
name: "projectName",
message: "project name",
default: project,
},
{
type: "confirm",
name: "isTs",
message: "是否支持typeScript",
},
])
.then((answers) => {
if (checkPath(answers.projectName)) {
console.log("文件已存在")
return
}
if (answers.isTs) {
downloadTemp("ts", answers.projectName)
} else {
downloadTemp("js", answers.projectName)
}
})
})
program.parse(process.argv)
Why should we write #!/usr/bin/env node in the first line?
This is a special comment used to tell the operating system to use the node interpreter to execute this file instead of explicitly calling the node command.
- utils.js
import fs from "node:fs"
import download from "download-git-repo"
import ora from "ora"
const spinner = ora("下载中...")
//验证路径
export const checkPath = (path) => {
return fs.existsSync(path)
}
//下载
export const downloadTemp = (branch, project) => {
spinner.start()
return new Promise((resolve, reject) => {
download(
`direct:https://gitee.com/chinafaker/vue-template.git#${branch}`,
project,
{ clone: true },
function (err) {
if (err) {
reject(err)
console.log(err)
}
resolve()
spinner.succeed("下载完成")
}
)
})
}
- package.json
"type": "module", //使用import需要设置这个
"bin": {
"vue-cli": "src/index.js"
},
Used to generate soft connections and mount them globally, so that the vue-cli command can be executed globally. It needs to be executed after the configuration is completed.
npm link


Nodejs Chapter 23 (Markdown to HTML)
Converting Markdown to HTML is a very common requirement
What is Markdown?
Markdown is a lightweight markup language that allows people to write documents in a plain text format that is easy to read and write.
We need to use three libraries to implement
- EJS: A powerful JavaScript template engine that can help us embed dynamic content in HTML. Using EJS, you can easily convert Markdown into beautiful HTML pages.
- Marked: A popular Markdown parser and compiler that can convert Markdown syntax into HTML markup. Marked is a powerful and easy-to-use library that provides you with rich options and extensions to meet various conversion needs.
- BrowserSync: A powerful development tool that helps you preview and synchronize your web page changes in real time. When you make edits to a Markdown file and convert it to HTML, BrowserSync can automatically refresh your browser, allowing you to instantly view the converted results.
ejs syntax
1. Pure script tag
<% code %>
Any js can be written in it for process control without any output.
<% alert('hello world') %> // 会执行弹框
2. Output HTML-escaped content
<%= value %> can be a variable
<%= a ? b : c %> can also be an expression
<%= a + b %>
That is, if the variable contains HTML characters such as '<'、'>', '&', etc., it will be escaped into character entities, such as < > &
Therefore, when using <%=, it is best to ensure that the content does not contain HTML characters.
const text = '<p>你好你好</p>'
<h2><%= text %></h2> // 输出 <p>你好你好</p> 插入 <h2> 标签中
3. Output unescaped content (original content)
<%-Fift text data %> is usually used to output rich text, that is, HTML content
It is mentioned above that <%= will escape HTML characters, so what if we just want to output a piece of HTML?
<%- will not parse HTML tags, nor will it escape characters and output them. Like the following example, Here I come. will be directly inserted into
in tag
const content = '<p>标签</p>'
<h2><%- content %></h2>
4. Introduce other templates
<%-inclade('*** file path')%>
Include template fragments relative to the template path.
Use the <%- include instruction instead of <% include to avoid escaping the output HTML code.
// 当前模版路径:./views/tmp.ejs
// 引入模版路径:./views/user/show.ejs
<ul>
<% users.forEach(function(user){ %>
<%- include('user/show', {user: user}); %>
<% }); %>
</ul>
5. Conditional judgment
<% if (condition1) { %>
...
<% } %>
<% if (condition1) { %>
...
<% } else if (condition2) { %>
...
<% } %>
// 举例
<% if (a && b) { %>
<p>可以直接放 html 内容</p>
<% } %>
<% if (a && b) { %>
<% console.log('也可以嵌套任意ejs模版语句') %>
<% } %>
6. Loop
<% for(var i = 0; i < target.length; i++){ %>
<%= i %> <%= target[i] %>
<% } %>
<% for(var i in jsArr) { %>
<script type="text/javascript" src="<%= jsArr[i] %>" ref="preload"></script>
<% } %>
// 推荐
<% for(var css of cssArr) { %>
<link rel="stylesheet" href="<%= css %>" />
<% } %>
- template.ejs
Initializing templates will be converted to html.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= title %></title>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<%- content %>
</body>
</html>
marked
Write a simple md document
### 标题
- test
Convert md to html
const marked = require("marked")
marked.parse(readme.toString()) //调用parse即可
browserSync
Create a browser and start a service. Set the root directory and index.html file
const browserSync = require("browser-sync")
const openBrowser = () => {
const browser = browserSync.create()
browser.init({
server: {
baseDir: "./",
index: "index.html",
},
})
return browser
}
index.css
The html code is available, but there is no universal css for universal markdown.
/* Markdown通用样式 */
/* 设置全局字体样式 */
body {
font-family: Arial, sans-serif;
font-size: 16px;
line-height: 1.6;
color: #333;
}
/* 设置标题样式 */
h1,
h2,
h3,
h4,
h5,
h6 {
margin-top: 1.3em;
margin-bottom: 0.6em;
font-weight: bold;
}
h1 {
font-size: 2.2em;
}
h2 {
font-size: 1.8em;
}
h3 {
font-size: 1.6em;
}
h4 {
font-size: 1.4em;
}
h5 {
font-size: 1.2em;
}
h6 {
font-size: 1em;
}
/* 设置段落样式 */
p {
margin-bottom: 1.3em;
}
/* 设置链接样式 */
a {
color: #337ab7;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
/* 设置列表样式 */
ul,
ol {
margin-top: 0;
margin-bottom: 1.3em;
padding-left: 2em;
}
/* 设置代码块样式 */
pre {
background-color: #f7f7f7;
padding: 1em;
border-radius: 4px;
overflow: auto;
}
code {
font-family: Consolas, Monaco, Courier, monospace;
font-size: 0.9em;
background-color: #f7f7f7;
padding: 0.2em 0.4em;
border-radius: 4px;
}
/* 设置引用样式 */
blockquote {
margin: 0;
padding-left: 1em;
border-left: 4px solid #ddd;
color: #777;
}
/* 设置表格样式 */
table {
border-collapse: collapse;
width: 100%;
margin-bottom: 1.3em;
}
table th,
table td {
padding: 0.5em;
border: 1px solid #ccc;
}
/* 添加一些额外的样式,如图片居中显示 */
img {
display: block;
margin: 0 auto;
max-width: 100%;
height: auto;
}
/* 设置代码行号样式 */
pre code .line-numbers {
display: inline-block;
width: 2em;
padding-right: 1em;
color: #999;
text-align: right;
user-select: none;
pointer-events: none;
border-right: 1px solid #ddd;
margin-right: 0.5em;
}
/* 设置代码行样式 */
pre code .line {
display: block;
padding-left: 1.5em;
}
/* 设置代码高亮样式 */
pre code .line.highlighted {
background-color: #f7f7f7;
}
/* 添加一些响应式样式,适应移动设备 */
@media only screen and (max-width: 768px) {
body {
font-size: 14px;
line-height: 1.5;
}
h1 {
font-size: 1.8em;
}
h2 {
font-size: 1.5em;
}
h3 {
font-size: 1.3em;
}
h4 {
font-size: 1.1em;
}
h5 {
font-size: 1em;
}
h6 {
font-size: 0.9em;
}
table {
font-size: 14px;
}
}
Complete code
const ejs = require("ejs") // 导入ejs库,用于渲染模板
const fs = require("node:fs") // 导入fs模块,用于文件系统操作
const marked = require("marked") // 导入marked库,用于将Markdown转换为HTML
const readme = fs.readFileSync("README.md") // 读取README.md文件的内容
const browserSync = require("browser-sync") // 导入browser-sync库,用于实时预览和同步浏览器
const openBrowser = () => {
const browser = browserSync.create()
browser.init({
server: {
baseDir: "./",
index: "index.html",
},
})
return browser
}
ejs.renderFile(
"template.ejs",
{
content: marked.parse(readme.toString()),
title: "markdown to html",
},
(err, data) => {
if (err) {
console.log(err)
}
let writeStream = fs.createWriteStream("index.html")
writeStream.write(data)
writeStream.close()
writeStream.on("finish", () => {
openBrowser()
})
}
)
renderings


Nodejs Chapter 24 (zlib)
In Node.js, the zlib module provides functions for data compression and decompression to reduce data transfer size and improve performance in applications. The module supports multiple compression algorithms, including Deflate, Gzip, and Raw Deflate.
The main functions of the zlib module are as follows:
- Data compression: Use the
zlibmodule to compress data using lossless compression algorithms (such as Deflate, Gzip) to reduce the size of the data. This is particularly useful in network transmission and disk storage, saving bandwidth and storage space. - Data decompression: The
zlibmodule also provides a decompression function for compressed data, which can restore the original data before compression. - Stream compression: The
zlibmodule supports data compression and decompression using the stream (Stream) method. This approach enables incremental processing of large files or network data streams without loading the entire data into memory. - Compression format support:
zlibmodule supports a variety of common compression formats, such as Gzip and Deflate. These formats are widely used in various application scenarios, such as content encoding of HTTP responses, file compression and decompression, etc.
Using the zlib module for data compression and decompression can help optimize application performance and resource utilization. By reducing the size of the data, you can reduce network transfer time and bandwidth consumption while reducing storage space on disk. In addition, the zlib module also provides a wealth of options and methods, allowing developers to perform flexible compression and decompression operations according to specific needs.
Code example
Compress a txt file gzip index.txt(439kb) Compressed.index.txt.gz (4b)
// 引入所需的模块
const zlib = require("zlib") // zlib 模块提供数据压缩和解压缩功能
const fs = require("node:fs") // 引入 Node.js 的 fs 模块用于文件操作
// 创建可读流和可写流
const readStream = fs.createReadStream("index.txt") // 创建可读流,读取名为 index.txt 的文件
const writeStream = fs.createWriteStream("index.txt.gz") // 创建可写流,将压缩后的数据写入 index.txt.gz 文件
// 使用管道将可读流中的数据通过 Gzip 压缩,再通过管道传输到可写流中进行写入
readStream.pipe(zlib.createGzip()).pipe(writeStream)
Unzip gzip
const readStream = fs.createReadStream("index.txt.gz")
const writeStream = fs.createWriteStream("index2.txt")
readStream.pipe(zlib.createGunzip()).pipe(writeStream)
Lossless compression deflate uses createDeflate method
const readStream = fs.createReadStream("index.txt") // 创建可读流,读取名为 index.txt 的文件
const writeStream = fs.createWriteStream("index.txt.deflate") // 创建可写流,将压缩后的数据写入 index.txt.deflate 文件
readStream.pipe(zlib.createDeflate()).pipe(writeStream)
Unzip deflate
const readStream = fs.createReadStream("index.txt.deflate")
const writeStream = fs.createWriteStream("index3.txt")
readStream.pipe(zlib.createInflate()).pipe(writeStream)
The difference between gzip and deflate
- Compression algorithm: Gzip uses the Deflate compression algorithm, which combines the LZ77 algorithm and Huffman coding. The LZ77 algorithm is used for replacement and quoting of repeated strings of data, while Huffman coding is used to further compress the data.
- Compression efficiency: Gzip compression generally has higher compression ratios because it uses Huffman coding to further compress the data. Huffman coding uses shorter codes to represent more common characters based on their frequency of occurrence, thereby reducing the size of the data.
- Compression speed: Compared to using Deflate alone, Gzip compression requires more calculation and processing time because it also requires a Huffman encoding step. Therefore, Deflate may be faster than Gzip in terms of compression speed.
- Application scenarios: Gzip compression is commonly used for file compression, network transmission and content encoding of HTTP responses. It is widely used for data transmission between web servers and browsers to reduce file size and improve network transmission efficiency.
http request compression
deflate before compression (8.2 kb) -> After compression (236b)
const zlib = require("zlib")
const http = require("node:http")
const server = http.createServer((req, res) => {
const txt = "小满zs".repeat(1000)
//res.setHeader('Content-Encoding','gzip')
res.setHeader("Content-Encoding", "deflate")
res.setHeader("Content-type", "text/plan;charset=utf-8")
const result = zlib.deflateSync(txt)
res.end(result)
})
server.listen(3000)
gizp Before compression (8.2 kb) -> Compressed (245b)
const zlib = require("zlib")
const http = require("node:http")
const server = http.createServer((req, res) => {
const txt = "小满zs".repeat(1000)
res.setHeader("Content-Encoding", "gzip")
//res.setHeader('Content-Encoding','deflate')
res.setHeader("Content-type", "text/plan;charset=utf-8")
const result = zlib.gzipSync(txt)
res.end(result)
})
server.listen(3000)
Nodejs Chapter 25 (http)
The "http" module is the core module in Node.js for creating and handling HTTP servers and clients. It makes building applications based on the HTTP protocol easier and more flexible.
- Create a web server: You can use the "http" module to create an HTTP server for serving web applications or websites. By listening to a specific port, the server can receive client requests and generate responses. You can handle different routes, request methods and parameters to implement custom business logic.
- Building a RESTful API: The "http" module makes building a RESTful API easy. You can define different endpoints of your API using HTTP request methods (such as GET, POST, PUT, DELETE, etc.) and paths. You can build powerful API services by parsing request parameters, verifying identity and permissions, and generating corresponding JSON or other data formats.
- Proxy server: The "http" module can also be used to create a proxy server to forward client requests to other servers. Proxy servers can be used in scenarios such as load balancing, caching, security filtering, or cross-domain requests. By adding logic on the proxy server, you can modify, log, or filter requests and responses.
- File server: The "http" module can be used to create a simple file server for serving static files (such as HTML, CSS, JavaScript, images, etc.). You can easily build a basic file server by reading the file and sending it as a response to the client.
Create http server
const http = require("node:http")
const url = require("node:url")
http
.createServer((req, res) => {})
.listen(98, () => {
console.log("server is running on port 98")
})
Our front-end commonly uses GET POST when making requests.
So how does nodejs distinguish between GET and POST?
http
.createServer((req, res) => {
//通过method 就可以了
if (req.method === "POST") {
} else if (req.method === "GET") {
}
})
.listen(98, () => {
console.log("server is running on port 98")
})
full version
const http = require("node:http") // 引入 http 模块
const url = require("node:url") // 引入 url 模块
// 创建 HTTP 服务器,并传入回调函数用于处理请求和生成响应
http
.createServer((req, res) => {
const { pathname, query } = url.parse(req.url, true) // 解析请求的 URL,获取路径和查询参数
if (req.method === "POST") {
// 检查请求方法是否为 POST
if (pathname === "/post") {
// 检查路径是否为 '/post'
let data = ""
req.on("data", (chunk) => {
data += chunk // 获取 POST 请求的数据
console.log(data)
})
req.on("end", () => {
res.setHeader("Content-Type", "application/json") // 设置响应头的 Content-Type 为 'application/json'
res.statusCode = 200 // 设置响应状态码为 200
res.end(data) // 将获取到的数据作为响应体返回
})
} else {
res.setHeader("Content-Type", "application/json") // 设置响应头的 Content-Type 为 'application/json'
res.statusCode = 404 // 设置响应状态码为 404
res.end("Not Found") // 返回 'Not Found' 作为响应体
}
} else if (req.method === "GET") {
// 检查请求方法是否为 GET
if (pathname === "/get") {
// 检查路径是否为 '/get'
console.log(query.a) // 打印查询参数中的键名为 'a' 的值
res.end("get success") // 返回 'get success' 作为响应体
}
}
})
.listen(98, () => {
console.log("server is running on port 98") // 打印服务器启动的信息
})
How to debug?

After the installation is complete, you can write simple code and send the request directly.
[POST | GET | PUT] [URL] [http version]
[request header]
[data passed]
# POST http://localhost:98/post/xxx HTTP/1.1
# Content-Type: application/json
# {
# "name":"小满zs"
# }
GET http://localhost:98/get?a=1&b=2 HTTP/1.1
Nodejs Chapter 26 (Reverse Proxy)
What is a reverse proxy?
Reverse Proxy is a network communication mode that acts as an intermediary between the server and the client, forwarding the client's request to one or more back-end servers and returning the back-end server's response to the client.
- Load balancing: The reverse proxy can distribute requests to multiple backend servers according to predefined algorithms to achieve load balancing. This avoids overloading one backend server and improves overall performance and availability.
- High availability: With a reverse proxy, requests can be forwarded to multiple backend servers to provide redundancy and failover. If one backend server fails, the proxy server can forward requests to other available servers, thus achieving high availability.
- Caching and performance optimization: Reverse proxy can cache static resources or frequently accessed dynamic content to reduce the load on the back-end server and improve response speed. It can also optimize network performance through techniques such as compression, merging, and resource optimization.
- Security: A reverse proxy can act as a firewall to protect backend servers from malicious requests and attacks. It filters malicious requests, detects and blocks attacks, and provides security authentication and access control.
- Domain name and path rewriting: The reverse proxy can rewrite the requested domain name and path according to specific rules to achieve URL routing and redirection. This is very useful for system architecture flexibility and maintainability.

Code implementation
Library used
http-proxy-middleware
npm install http-proxy-middleware
Root directory custom configuration file
xm.config.js
Configure proxy proxy
module.exports = {
server: {
proxy: {
//代理的路径
"/api": {
target: "http://localhost:3000", //转发的地址
changeOrigin: true, //是否有跨域
},
},
},
}
index.js implementation layer
const http = require("node:http")
const fs = require("node:fs")
const url = require("node:url")
const html = fs.readFileSync("./index.html") //给html文件起个服务
const { createProxyMiddleware } = require("http-proxy-middleware")
const config = require("./xm.config.js")
const server = http.createServer((req, res) => {
const { pathname } = url.parse(req.url)
const proxyList = Object.keys(config.server.proxy) //获取代理的路径
if (proxyList.includes(pathname)) {
//如果请求的路径在里面匹配到 就进行代理
const proxy = createProxyMiddleware(config.server.proxy[pathname]) //代理
proxy(req, res)
return
}
console.log(proxyList)
res.writeHead(200, {
"Content-Type": "text/html",
})
res.end(html) //返回html
})
server.listen(80) //监听端口
test.js because we forward from port 80 to port 3000
const http = require("node:http")
const url = require("node:url")
http
.createServer((req, res) => {
const { pathname } = url.parse(req.url)
if (pathname === "/api") {
res.end("success proxy")
}
})
.listen(3000)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
fetch("/api")
.then((res) => res.text())
.then((res) => {
console.log(res)
})
</script>
</body>
</html>
So we get from 80 agents to 3000 port and there's no cross-border.

Nodejs Chapter 27 (Separation of movement and static)
What is dynamic and static separation?
Dynamic and static separation is an optimization technique commonly used in web server architecture to improve the performance and scalability of the website. It is based on a simple principle: process and distribute dynamically generated content (such as dynamic web pages, API requests) and static resources (such as HTML, CSS, JavaScript, image files) separately.
By storing dynamic content and static resources on different servers or services and using different processing mechanisms, the processing efficiency and response speed of the website can be improved. The benefits of this separation include:
- Performance Optimization: Separating static resources from dynamic content can improve the loading speed of the website. Since static resources tend to be immutable, caching mechanisms can be used to store them in a CDN (content delivery network) or browser cache, thereby reducing the overhead of network requests and data transmission.
- Load Balancing: By distributing dynamic requests to different servers or services, the load of the server can be balanced and the scalability and fault tolerance of the entire system can be improved.
- Security: Separate processing of dynamic requests and static resources can improve the security of the system. Static resources are typically publicly accessible, while dynamic requests may involve sensitive data or require specific authentication and authorization. By separating static resources from dynamic content, access control and security policies can be better managed.
Methods to achieve dynamic and static separation
- Use reverse proxy servers (such as Nginx, Apache) to forward static requests and dynamic requests to different backend servers or services.
- Deploy static resources to CDN and distribute static resources through CDN to reduce the load on the source server.
- Use dedicated static file servers (such as Amazon S3, Google Cloud Storage) to store and serve static resources, and leave dynamic requests to the application server for processing.
Code writing
The following is a sample code written in Node.js that demonstrates how to handle dynamic and static requests:
import http from "node:http" // 导入http模块
import fs from "node:fs" // 导入文件系统模块
import path from "node:path" // 导入路径处理模块
import mime from "mime" // 导入mime模块
const server = http.createServer((req, res) => {
const { url, method } = req
// 处理静态资源
if (method === "GET" && url.startsWith("/static")) {
const filePath = path.join(process.cwd(), url) // 获取文件路径
const mimeType = mime.getType(filePath) // 获取文件的MIME类型
console.log(mimeType) // 打印MIME类型
fs.readFile(filePath, (err, data) => {
// 读取文件内容
if (err) {
res.writeHead(404, {
"Content-Type": "text/plain", // 设置响应头为纯文本类型
})
res.end("not found") // 返回404 Not Found
} else {
res.writeHead(200, {
"Content-Type": mimeType, // 设置响应头为对应的MIME类型
"Cache-Control": "public, max-age=3600", // 设置缓存控制头
})
res.end(data) // 返回文件内容
}
})
}
// 处理动态资源
if ((method === "GET" || method === "POST") && url.startsWith("/api")) {
// ...处理动态资源的逻辑
}
})
server.listen(80) // 监听端口80
Because the mime type corresponding to each file is different, there are many if written by hand. However, the powerful nodejs community provides the mime library, which can help us directly analyze the corresponding mime type through the suffix, and then we use strong caching to let the browser cache static resources.
Common mime type display
- 文本文件:
- text/plain:纯文本文件
- text/html:HTML 文件
- text/css:CSS 样式表文件
- text/javascript:JavaScript 文件
- application/json:JSON 数据
- 图像文件:
- image/jpeg:JPEG 图像
- image/png:PNG 图像
- image/gif:GIF 图像
- image/svg+xml:SVG 图像
- 音频文件:
- audio/mpeg:MPEG 音频
- audio/wav:WAV 音频
- audio/midi:MIDI 音频
- 视频文件:
- video/mp4:MP4 视频
- video/mpeg:MPEG 视频
- video/quicktime:QuickTime 视频
- 应用程序文件:
- application/pdf:PDF 文件
- application/zip:ZIP 压缩文件
- application/x-www-form-urlencoded:表单提交数据
- multipart/form-data:多部分表单数据
Nodejs Chapter 28 (Mail Service)
Email service plays an important role in our work
-
- Task allocation and tracking: Email service can be used to allocate tasks, assign work and track project progress. Through email, you can send task lists, work instructions, and progress updates to ensure team members understand their responsibilities and task requirements, and to monitor the completion of work.
-
- Error reporting and troubleshooting: When an error or exception occurs in the program, programmers can send error reports to team members or relevant parties via email. This helps teams understand the nature of the issue, steps to reproduce it, and the surrounding environment to better troubleshoot and fix it. Detailed error messages, stack traces, and other relevant information can be provided in the email so that other team members can better understand the issue and provide solutions.
-
- Automated build and continuous integration: During the continuous integration and automated build process, the email service can be used to notify team members of build status, unit test results, code coverage and other information. If the build fails or a warning occurs, the system can automatically send an email to notify relevant personnel so that appropriate measures can be taken in a timely manner.
Code writing
Need to use library
npm install js-yaml
npm install nodemailer
Our email account (password | authorization code) cannot be written in plain text in the code and is usually stored in a yaml file or environment variable.
js-yaml parses yaml files
pass: 授权码 | 密码
user: xxxxx@qq.com 邮箱账号
import nodemailder from "nodemailer"
import yaml from "js-yaml"
import fs from "node:fs"
import http from "node:http"
import url from "node:url"
const mailConfig = yaml.load(fs.readFileSync("./mail.yaml", "utf8"))
const transPort = nodemailder.createTransport({
service: "qq",
port: 587,
host: "smtp.qq.com",
secure: true,
auth: {
pass: mailConfig.pass,
user: mailConfig.user,
},
})
http
.createServer((req, res) => {
const { pathname } = url.parse(req.url)
if (req.method === "POST" && pathname == "/send/mail") {
let mailInfo = ""
req.on("data", (chunk) => {
mailInfo += chunk.toString()
})
req.on("end", () => {
const body = JSON.parse(mailInfo)
transPort.sendMail({
to: body.to,
from: mailConfig.user,
subject: body.subject,
text: body.text,
})
res.end("ok")
})
}
})
.listen(3000)
nodemailder.createTransport creates a mail service. Here we use qq as an example.
QQ mail service documentation
POP3/SMTP setting method
Username/Account: Your complete QQ email address
Password: Generated Authorization Code
E-mail address: Your complete email address of QQ mailbox
Receive mail server: pop.qq.com, using SSL, port number 995
Outgoing mail server: smtp.qq.com, using SSL, port number 465 or 587
Authorization code generation


Test sending
POST http://localhost:3000/send/mail HTTP/1.1
Content-Type: application/json
{
"to":"xxxxx@qq.com",
"subject":"标题",
"text":"我想你了,xxxxxx"
}

Nodejs Chapter 29 (express)
What is express?
Express is a popular Node.js web application framework for building flexible and scalable web applications and APIs. It was created based on Node.js's HTTP module, simplifying the process of handling HTTP requests, responses, and middleware.
- Simple and flexible: Express provides a simple and intuitive API, making building web applications easy and fast. It provides a flexible set of routing and middleware mechanisms that allow developers to customize and organize the application's behavior according to their needs.
- Routing and middleware: Express uses routing and middleware to handle HTTP requests and responses. Developers can define routing rules to map specific URL paths to corresponding processing functions. At the same time, middleware allows developers to perform logic such as authentication, logging, and error handling before or after the request reaches the route handler function.
- Routing modularization: Express supports routing modularization so that applications can be grouped according to different functions or modules. This can improve the organization and maintainability of the code, making collaborative development by multiple people more convenient.
- View engine support: Express can be integrated with various template engines, such as EJS, Pug (formerly Jade), Handlebars, etc. This allows developers to easily generate dynamic HTML pages and dynamically render data into templates.
- Middleware ecosystem: Express has a huge middleware ecosystem, and developers can use various middleware to extend and enhance the functionality of the application, such as authentication, session management, logging, static file serving, etc.
Encoding
- Start an http service
import express from "express"
const app = express() //express 是个函数
app.listen(3000, () => console.log("Listening on port 3000"))
-Write get post interface
app.get("/", (req, res) => {
res.send("get")
})
app.post("/create", (req, res) => {
res.send("post")
})
- Accept parameters from the front end
app.use(express.json()) //如果前端使用的是post并且传递json 需要注册此中间件 不然是undefined
app.get("/", (req, res) => {
console.log(req.query) //get 用query
res.send("get")
})
app.post("/create", (req, res) => {
console.log(req.body) //post用body
res.send("post")
})
//如果是动态参数用 params
app.get("/:id", (req, res) => {
console.log(req.params)
res.send("get id")
})
Modularity
During normal development, we will definitely not write the code into a module. Express allows the route handler to be split into multiple modules, and each module is responsible for processing specific routes. By splitting route handlers into modules, the code logic can be made clearer and easier to maintain and extend.
src
--user.js
--list.js
app.js
src/user.js
import express from "express"
const router = express.Router() //路由模块
router.post("/login", (req, res) => {
res.send("login")
})
router.post("/register", (req, res) => {
res.send("register")
})
export default router
app.js
import express from "express"
import User from "./src/user.js"
const app = express()
app.use(express.json())
app.use("/user", User)
app.get("/", (req, res) => {
console.log(req.query)
res.send("get")
})
app.get("/:id", (req, res) => {
console.log(req.params)
res.send("get id")
})
app.post("/create", (req, res) => {
console.log(req.body)
res.send("post")
})
app.listen(3000, () => console.log("Listening on port 3000"))
Middleware
Middleware is a key concept. Middleware is a function that processes HTTP requests and responses. It is located between the request and the final routing processing function. It can modify the request and response, perform additional logic, or perform other tasks.
The middleware function receives three parameters: req (request object), res (response object) and next (next middleware function). By calling the next() method, the middleware can pass control to the next middleware function. If the middleware does not call the next() method, the request will be aborted and will not continue to the next middleware or route handler function.
- Implement a logging middleware
npm install log4js
log4js is a popular logging library for Node.js applications that provides flexible and configurable logging functionality. log4js allows you to record different levels of log messages in your application and output log messages to multiple targets, such as console, file, database, etc.
express\middleware\logger.js
import log4js from "log4js"
// 配置 log4js
log4js.configure({
appenders: {
out: {
type: "stdout", // 输出到控制台
layout: {
type: "colored", // 使用带颜色的布局
},
},
file: {
type: "file", // 输出到文件
filename: "./logs/server.log", // 指定日志文件路径和名称
},
},
categories: {
default: {
appenders: ["out", "file"], // 使用 out 和 file 输出器
level: "debug", // 设置日志级别为 debug
},
},
})
// 获取 logger
const logger = log4js.getLogger("default")
// 日志中间件
const loggerMiddleware = (req, res, next) => {
logger.debug(`${req.method} ${req.url}`) // 记录请求方法和URL
next()
}
export default loggerMiddleware
app.js
import express from "express"
import User from "./src/user.js"
import loggerMiddleware from "./middleware/logger.js"
const app = express()
app.use(loggerMiddleware)

Nodejs Chapter 30 (Anti-hotlinking)
Hotlinking refers to directly linking to pictures, videos or other media files on other websites in web pages or other network resources, thereby displaying them on your own web page. This behavior usually brings additional bandwidth consumption and resource waste to the linked website, and may infringe the copyright of the original website.
To prevent hotlinking, website administrators can take some measures:
- Through HTTP reference checking: The website can check the source of the HTTP request and refuse to provide the resource if the source URL does not match the legal source. This can be achieved through server configuration files or specific scripts.
- Use Referrer check: The website can check the Referrer field in the HTTP request, which indicates the source page of the requested resource. If the Referrer field does not meet expectations, the resource will be refused. This approach can be implemented in a server configuration file or script.
- Use access control list (ACL): Website administrators can configure the server's access control list to only allow specific domain names or IP addresses to access resources, and requests from other sources will be rejected.
- Use anti-hotlinking plug-ins or scripts: Some website platforms and content management systems provide special plug-ins or scripts to prevent hotlinking. These tools can be configured as needed to block hotlink requests from unauthorized websites.
- Use watermark technology: Adding watermarks to pictures or videos can help identify hotlinking behavior and remind users of the source of the resource.
Encoding
- The first step is to initialize the static resource directory
express.static
import express from "express"
const app = express()
//自定义前缀 初始化目录
app.use("/assets", express.static("static"))
app.listen(3000, () => {
console.log("listening on port 3000")
})


Add anti-leeching
Anti-leeching is generally mainly about verifying host or referer
import express from "express"
const app = express()
const whitelist = ["localhost"]
// 防止热链中间件
const preventHotLinking = (req, res, next) => {
const referer = req.get("referer") // 获取请求头部中的 referer 字段
if (referer) {
const { hostname } = new URL(referer) // 从 referer 中解析主机名
if (!whitelist.includes(hostname)) {
// 检查主机名是否在白名单中
res.status(403).send("Forbidden") // 如果不在白名单中,返回 403 Forbidden
return
}
}
next() // 如果在白名单中,继续处理下一个中间件或路由
}
app.use(preventHotLinking) // 应用防止热链中间件
app.use("/assets", express.static("static")) // 处理静态资源请求
app.listen(3000, () => {
console.log("Listening on port 3000") // 启动服务器,监听端口3000
})
127.0.0.1 No permissions

localhost has permissions

Nodejs Chapter 31 (Response Headers and Request Headers)
Response header
HTTP response headers are metadata information sent in HTTP responses to describe the characteristics, content, and behavior of the response. They appear as key-value pairs, each of which consists of a header field and a corresponding value.
For example the following example
Access-Control-Allow-Origin:*
Cache-Control:public, max-age=0, must-revalidate
Content-Type:text/html; charset=utf-8
Server:nginx
Date:Mon, 08 Jan 2024 18:32:47 GMT
The relationship between response headers and cross-domain
- cors
Cross-Origin Resource Sharing (CORS) is a mechanism used to implement permission control for cross-domain requests to access resources in browsers. When a web page initiates a cross-domain request through XMLHttpRequest or Fetch API, the browser will restrict it based on the Same-Origin Policy. The same source (agreement, domain name and port) of the co-source policy request must be the same as the source of the resource, otherwise the request will be rejected by the browser
- Send a request
fetch("http://localhost:3000/info")
.then((res) => {
return res.json()
})
.then((res) => {
console.log(res)
})
- Express writes a get interface
import express from "express"
const app = express()
app.get("/info", (req, res) => {
res.json({
code: 200,
})
})
app.listen(3000, () => {
console.log("http://localhost:3000")
})
It was found that there was an error. According to the same origin policy, we saw The protocol, the domain name, but the port doesn't match.. The ports cannot be consistent and there will be conflicts. Otherwise, it is a project where the front and back ends are not separated. The front and back ends codes are put together and only use one port. However, we are separated and cannot do this.

At this time, we need back-end support to allow cross-domain request resources to be released.
Access-Control-Allow-Origin: * | Origin
Add the following Response Header to allow localhost 5500 access
app.use("*", (req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "http://localhost:5500") //允许localhost 5500 访问
next()
})
Result returned

Request header
By default, cors only supports the client to send the following nine request headers to the server.
tips no application/json
- Accept: Specify the content types that the client can handle.
- Accept-Language: Specifies the natural language preferred by the client.
- Content-Language: Specifies the natural language of the request or response entity.
- Content-Type: Specifies the media type of the request or response entity.
- DNT (Do Not Track): Indicates that the client does not want to be tracked.
- Origin: Indicates the source of the request (protocol, domain name and port).
- User-Agent: Contains information about the user agent that initiated the request.
- Referer: Indicates the source URL of the current request.
Content-type: application/x-www-form-urlencoded | multipart/form-data | text/plain
If the client needs to support additional requests then we need to support it on the client side
;("Access-Control-Allow-Headers", "Content-Type") //支持application/json
Request method support
Our server only supports GET POST HEAD OPTIONS requests by default
For example, we follow restFui to support PATCH or other requests
add patch
app.patch("/info", (req, res) => {
res.json({
code: 200,
})
})
Send patch
fetch("http://localhost:3000/info", {
method: "PATCH",
})
.then((res) => {
return res.json()
})
.then((res) => {
console.log(res)
})
I found an error saying that patch is not in our methods.

Modify as follows
;("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,PATCH")

Preflight request OPTIONS
The main purpose of the preflight request is to ensure the security of cross-domain requests. It needs to meet certain conditions before it will be triggered.
- Custom request methods: When using non-simple request methods (Simple Request Methods), such as PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH, etc., the browser will send a preflight request.
- Custom request header fields: When the request contains custom header fields, the browser will send a preflight request. Custom header fields refer to fields that do not belong to the simple request header field list, for example, Content-Type is application/json, Authorization, etc.
- Requests with credentials: When the request requires sending and receiving credentials in a cross-domain environment (for example, containing credential information such as cookies, HTTP authentication, etc.), the browser will send a preflight request.
- Try sending a preflight request
fetch("http://localhost:3000/info", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ name: "xmzs" }),
})
.then((res) => {
return res.json()
})
.then((res) => {
console.log(res)
})
- express
app.post("/info", (req, res) => {
res.json({
code: 200,
})
})
Found an error reported

Because application/json does not belong to the cors category and needs manual support
;("Access-Control-Allow-Headers", "Content-Type")


Custom response header
When we make demands, we will definitely encounter back-end custom response headers
app.get("/info", (req, res) => {
res.set("xmzs", "1")
res.json({
code: 200,
})
})

How does the front end read it?
fetch("http://localhost:3000/info")
.then((res) => {
const headers = res.headers
console.log(headers.get("xmzs")) //读取自定义响应头
return res.json()
})
.then((res) => {
console.log(res)
})
It was found to be null. This is because the backend did not throw the response header, so the backend needs to add a thrown field.
app.get("/info", (req, res) => {
res.set("xmzs", "1")
res.setHeader("Access-Control-Expose-Headers", "xmzs")
res.json({
code: 200,
})
})

SSE Technology
Server-Sent Events (SSE) is a mechanism that implements one-way event flow between the client and the server, allowing the server to proactively send event data to the client. In SSE, you can use custom events to send event data of specific types.
WebSocket is full-time, that is, the front end can send to the back end in real time, the back end can send to the front end in real time, the SSE is a stand-alone communication, the back end can send to the front end in real time
- express
Add the response header
text/event-streamto become sse event event name data data sent
app.get("/sse", (req, res) => {
res.setHeader("Content-Type", "text/event-stream")
res.status(200)
setInterval(() => {
res.write("event: test\n")
res.write("data: " + new Date().getTime() + "\n\n")
}, 1000)
})
Front end accepts
const sse = new EventSource("http://localhost:3000/sse")
sse.addEventListener("test", (event) => {
console.log(event.data)
})

Nodejs Chapter 32 (Database)
MySQL is an open source Relationship Database management system (RDBMS) that is one of the most popular database systems. MySQL is widely used in web applications and other applications that require reliable data storage.
The following are some important features and concepts of MySQL database:
- Database: MySQL is a database management system used to create and manage databases. A database is an organizational structure used to store and manage data.
- Table: Data in the database is organized into tables. A table consists of rows and columns, with rows representing records and columns representing fields.
- SQL: MySQL uses Structured Query Language (SQL) for database operations. SQL is a language used to define, manipulate, and query databases.
- Data types: MySQL supports various data types, such as integers, floating point numbers, strings, dates and times, etc. Each column has its own data type.
- Indexes: MySQL allows the creation of indexes to speed up data retrieval. An index is a data structure that sorts the values of one or more columns in a table.
- Primary Key: The primary key is the unique identifier in the table. It is used to ensure that each record in the table has a unique identity.
- Foreign keys: Foreign keys are used to establish associations between tables. It defines the relationship between columns in one table and columns in another table.
- Trigger: A trigger is an operation defined in the database that automatically executes when a specific event occurs. For example, when a new record is inserted into the table, a trigger can be fired to perform other actions.
- Stored procedures: A stored procedure is a set of precompiled SQL statements that can be reused in the database. It can accept parameters and return results.
- Backup and recovery: MySQL provides tools and commands to back up and restore the database to ensure data security and reliability.

What is a relational database?
In a relational database, data is stored in a structured manner, where each table consists of a set of columns (fields) and a set of rows (records). Each column defines the type and properties of the data, and each row represents a specific data instance. Relationships between tables are established using primary keys and foreign keys. The primary key is a column that uniquely identifies each row in the table, while the foreign key is a column that points to the primary key of other tables and is used to establish an association between tables.
Installation process

scroll below




Default port 3306

Set password

Add mysql service and remember the name (MySQL83)

Just keep going down

After the installation is complete, check whether the Mysql service is turned on services.msc

Why do you want everyone to remember the name MySQL83? Because it is the name of the service. If there is a problem, you can check the service.

Then configure the environment variables

Test Mysql and enter the password
mysql -uroot -p

success
Visual tool installation
Open VScode
Select the extension, search database and install Database Client


Create new library



Create new table

Insert data



Nodejs Chapter 33 (sql statement)
SQL (Structured Query Language) is a language used to manage relational database systems. It is a standardized language used to perform various database operations, including data query, insert, update, delete, etc.
Database operations
-Create database
create database 库名

If repeated creation is performed, it will fail and repeated creation is not allowed.

Avoid this problem if not exists
create database if not exists `xiaoman`

If the database does not exist, create it, if it exists, do nothing, I'd rather not do it than make a mistake..
Add character set utf-8
create database `xiaoman`
default character set = 'utf8mb4';
Data table
- Create table
CREATE TABLE `user` (
id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
name varchar(100) COMMENT '名字',
age int COMMENT '年龄',
address varchar(255) COMMENT '地址',
create_time timestamp DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间'
) COMMENT '用户表'
parse
create table table name (
idfield nameintdata type represents numeric typeNOT NULL(cannot be empty)AUTO_INCREMENT(id increases automatically)PRIMARY KEY(id is the primary key)name(field name)varchar(100)string type 100 charactersCOMMENT(comment)age(field name)intdata type represents the numeric typeCOMMENT(comment)create_time(field name)timestamp(timestamp)DEFAULT CURRENT_TIMESTAMP(auto-fill creation time)
)

- Modify table name
ALTER TABLE `user` RENAME `user2`;

- Add column
ALTER TABLE `user` Add COLUMN `hobby` VARCHAR(200) ;

- Delete columns
ALTER TABLE `user` DROP COLUMN `hobby`;

- Edit columns
ALTER TABLE `user` MODIFY COLUMN `age` VARCHAR(255) NULL COMMENT '年龄2';

Nodejs Chapter 34 (Query)
So far we have learned the basic operations of the database, as well as the basic statements of libraries and tables. However, for Mysql, the most commonly used are the add, delete, modify and query statements. Today we will learn the add, delete, modify and query statements.
Query
Query is the most frequently used statement
Query a single column
SELECT `name` FROM `user`;
Query multiple columns, separated by commas
SELECT `name`,`id` FROM `user`;

Query all columns *
SELECT * FROM `user`;

Column alias as
SELECT `name` as `user_name`,`id` as `user_id` FROM `user`;

Sort
ORDER BY [field name] desc Descending order (from large to small) asc Ascending order (from small to large)
SELECT * FROM `user` ORDER BY id DESC;

Limit query results
limit [start line] [limit number of items]
When using limit, it starts from 0, just like an array.
SELECT * FROM `user` LIMIT 1,3

Conditional query
We need to put Search Conditions in the WHERE clause. For example, query the value corresponding to the name field Xiaoman
Exact match
SELECT * FROM `user` WHERE name = "大满";

Joint query with multiple conditions
For example, I want to query people whose name is Xiaoman and whose age is under 20 years old.

- and operator
When given multiple search conditions, we sometimes need to query a certain record only when it meets all search conditions. In this case, we can use the and operator to connect multiple search conditions.
SELECT * FROM `user` WHERE name = '小满' AND age <= 20;
- or operator
When given multiple search conditions, we sometimes need to add a certain record to the result set when it meets a certain search condition. In this case, we can use the OR operator to connect multiple search conditions.
SELECT * FROM `user` WHERE name = '小满' OR age <= 22;
Fuzzy query
In MySQL, the "LIKE" operator is used to fuzzy match strings. The percent sign (%) is used as a wildcard character to represent a placeholder for any character (including zero or more characters).
When you use the "LIKE" operator, you can use the percent sign in a pattern to match one or more characters. Here are some examples of using the percent sign:
- "Full%": Matches a string starting with "Full", which can be followed by any character.
- "%full": matches a string ending with "full", which can be preceded by any character.
- "%full%": matches a string containing "full" at any position, and can be preceded and followed by any characters.
SELECT * FROM `user` WHERE name LIKE '%满%';

Nodejs Chapter 35 (Additions, Deletions and Modifications)
In the previous chapter, we learned about database query statements. In this chapter, we learn about adding, deleting, and modifying statements.
New
In this statement, we clarify the order of insertion. The first field corresponds to name, the second hobby, the third age, and the values in values correspond to it.
INSERT INTO user(`name`,`hobby`,`age`) VALUES('xiaoman','basketball',18)

Insert null value
When designing the table structure, we allow name age hobby to be null, so we can also insert null values.
INSERT INTO user(`name`,`hobby`,`age`) VALUES(NULL,NULL,NULL)

Insert multiple pieces of data separated by commas
INSERT INTO user(`name`,`hobby`,`age`) VALUES(NULL,NULL,NULL),('xiaoman','basketball',18)

Delete
Delete the record with id 11
DELETE FROM `user` WHERE id = 11;

Batch delete
DELETE FROM `user` WHERE id IN (8,9,10);

Update data
The updated field uses = assignment, where determines the updated regulations
UPDATE `user` SET name='麒麟哥',age=30,hobby='篮球' WHERE id = 12;

Nodejs Chapter 36 (Expressions and Functions)
Expression
A MySQL expression is a calculation or logical expression used in the MySQL database. They can be used to query, update, and filter data, as well as perform conditional judgments and calculations.
- Arithmetic expressions: Basic mathematical operations such as addition, subtraction, multiplication and division can be performed. For example:
SELECT col1 + col2 AS sum FROM table_name; - String expression: You can perform operations on strings, such as concatenation, interception and replacement. For example:
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM table_name; - Logical expression: used to perform conditional judgment and return a Boolean value (TRUE or FALSE). For example:
SELECT * FROM table_name WHERE age > 18 AND gender = 'Male'; - Conditional expression: used to return different results based on conditions. For example:
SELECT CASE WHEN age < 18 THEN 'Minor' ELSE 'Adult' END AS age_group FROM table_name; - Aggregation function expressions: used to calculate aggregate values of a data set, such as sum, average, maximum and minimum values. For example:
SELECT AVG(salary) AS average_salary FROM table_name; - Time and date expressions: used to process time and date data, such as extracting years, months or calculating date differences. For example:
SELECT YEAR(date_column) AS year FROM table_name;
For example, when querying, add the value 100
SELECT age + 100 FROM `user`;

If you want to change the column name, you can use as
SELECT age + 100 as age FROM `user`;

Function
MySQL provides a large number of built-in functions for calculation, transformation and processing when querying and manipulating data. The following are some commonly used MySQL function classifications and their examples:
- String functions:
CONCAT(str1, str2, ...): Concatenate multiple strings.SUBSTRING(str, start, length): Extract substring from string.UPPER(str): Convert string to uppercase.LOWER(str): Convert string to lowercase.LENGTH(str): Returns the length of the string.
- Numerical functions:
ABS(x): Returns the absolute value of x.ROUND(x, d): Round x to d decimal places.CEILING(x): Returns the smallest integer not less than x.FLOOR(x): Returns the largest integer not larger than x.RAND(): Returns a random number.
- Date and time functions:
NOW(): Returns the current date and time.CURDATE(): Returns the current date.CURTIME(): Returns the current time.DATE_FORMAT(date, format): Format the date to the specified format.DATEDIFF(date1, date2): Calculates the difference in days between two dates.
- Conditional function:
IF(condition, value_if_true, value_if_false): Return different values based on conditions.CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ELSE result END: Return different results based on conditions.
- Aggregation function:
-
COUNT(expr): Count the number of rows that meet the conditions. -
SUM(expr): Calculates the sum of an expression. -
AVG(expr): Calculates the average of an expression. -
MAX(expr): Returns the maximum value of the expression. -
MIN(expr): Returns the minimum value of the expression. -
Returns a random number

- Sum

- String concatenation

- Get the total number

Nodejs Chapter 37 (Subqueries and Joined Tables)
Subquery
Subquery, also known as Nested Query, refers to nesting another complete query statement within a query statement. A subquery can be thought of as the result set of a query, which can be used as part of an outer query to further filter, calculate, or manipulate data.
Subqueries usually appear in the WHERE clause, FROM clause, HAVING clause, or SELECT clause of the main query to provide more complex query logic. Subqueries can dynamically generate result sets based on the results of the main query, used to filter and match data, or used as parameters of functions.
A subquery can return a single value, a column of values, a row of values, or a result set, depending on the syntax and usage of the subquery. Depending on the type of results returned by the subquery, it can be compared with other expressions from the main query, concatenated, or used as a condition for filtering.
Our previous cases were queried in one table. In reality, everything will not be put in one table, but will be divided into tables, and even divided into databases and tables, reading and writing will be separated, etc.
Case query photo table by name
photo table data

user table data

Association is the id of the user table and the user id of the photo table
But now we need to query the data of the photo table by name. But what can we do if the photo table does not store names?
SubQuery
Our idea is to query the id of the user table by name, and then query the user_id of photo through the id of the user table. That's it.
SELECT * FROM `photo` WHERE `user_id` = (SELECT id FROM `user` WHERE name = '小满')

Join table
Mysql's connected tables are divided into inner joins, outer joins, and cross joins
- For the two tables of
Inner Connection, the record in the driver table cannot find a matching record in the driven table, and the record will not be added to the final result set. The connections we mentioned above are all so-calledInner Connection. - For the two tables of
External connection, the records in the driving table still need to be added to the result set even if there are no matching records in the driven table. Cross-connectionrefers to a connection without any connection conditions between two or more tables. Simply put,Cross-connectionallows you to query all possible combinations.
Inner join
SELECT * FROM `user`, `photo` WHERE `user`.`id` = `photo`.`user_id`

Outer join
Left Connection
Syntax rules LEFT JOIN [joined table] ON [joining conditions]
And use the first table as the driven table Driver Table. If there is no value, null is added.
SELECT * FROM `user` LEFT JOIN `table` ON `user`.`id` = `table`.`user_id`

Right Connect
Syntax rules LEFT JOIN [joined table] ON [joining conditions]
And use the second table as the driven table Driver Table and ignore it if there is no value.
SELECT * FROM `user` RIGHT JOIN `table` ON `user`.`id` = `table`.`user_id`

Nodejs Chapter 38 (mysql2)
In the previous chapter, the basic knowledge of mysql has been supplemented. Now, we need to connect mysql to express and nodejs.
Install dependencies
npm install mysql2 express js-yaml
- mysql2 is used to connect to mysql and write sq statements
- Express is used to provide interfaces for additions, deletions and modifications.
- js-yaml is used to write configuration files
Write code
db.config.yaml
db:
host: localhost #主机
port: 3306 #端口
user: root #账号
password: "123456" #密码 一定要字符串
database: xiaoman # 库
index.js
import mysql2 from "mysql2/promise"
import fs from "node:fs"
import jsyaml from "js-yaml"
import express from "express"
const yaml = fs.readFileSync("./db.config.yaml", "utf8")
const config = jsyaml.load(yaml)
const sql = await mysql2.createConnection({
...config.db,
})
const app = express()
app.use(express.json())
//查询接口 全部
app.get("/", async (req, res) => {
const [data] = await sql.query("select * from user")
res.send(data)
})
//单个查询 params
app.get("/user/:id", async (req, res) => {
const [row] = await sql.query(`select * from user where id = ?`, [
req.params.id,
])
res.send(row)
})
//新增接口
app.post("/create", async (req, res) => {
const { name, age, hobby } = req.body
await sql.query(`insert into user(name,age,hobby) values(?,?,?)`, [
name,
age,
hobby,
])
res.send({ ok: 1 })
})
//编辑
app.post("/update", async (req, res) => {
const { name, age, hobby, id } = req.body
await sql.query(`update user set name = ?,age = ?,hobby = ? where id = ?`, [
name,
age,
hobby,
id,
])
res.send({ ok: 1 })
})
//删除
app.post("/delete", async (req, res) => {
await sql.query(`delete from user where id = ?`, [req.body.id])
res.send({ ok: 1 })
})
const port = 3000
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
index.http
Convenient test interface
# 查询全部
GET http://localhost:3000/ HTTP/1.1
# 单个查询
GET http://localhost:3000/user/2 HTTP/1.1
# 添加数据
POST http://localhost:3000/create HTTP/1.1
Content-Type: application/json
{
"name":"张三",
"age":18
}
# 更新数据
POST http://localhost:3000/update HTTP/1.1
Content-Type: application/json
{
"name":"法外狂徒",
"age":20,
"id":23
}
#删除
# POST http://localhost:3000/delete HTTP/1.1
# Content-Type: application/json
# {
# "id":24
# }
Subsequent update plan

Nodejs Chapter 39 (knex)
knex
Knex is a JavaScript-based Query Generator that allows you to use JavaScript code to generate and execute SQL query statements. It provides a simple and intuitive way to interact with relational databases without writing SQL statements directly. You can use Knex to define table structures, perform queries, insert, update and delete data and other operations.
Installation and setup of Knex
knex supports multiple databases pg sqlite3 mysql2 oracledb tedious
Just install the corresponding database for whatever database you want to use.
#安装knex
$ npm install knex --save
#安装你用的数据库
$ npm install pg
$ npm install pg-native
$ npm install sqlite3
$ npm install better-sqlite3
$ npm install mysql
$ npm install mysql2
$ npm install oracledb
$ npm install tedious
Connect to database
import knex from "knex"
const db = knex({
client: "mysql2",
connection: config.db,
})
db:
user: root
password: "123456"
host: localhost
port: 3306
database: xiaoman
Define table structure
db.schema
.createTable("list", (table) => {
table.increments("id") //id自增
table.integer("age") //age 整数
table.string("name") //name 字符串
table.string("hobby") //hobby 字符串
table.timestamps(true, true) //创建时间和更新时间
})
.then(() => {
console.log("创建成功")
})
Implement additions, deletions, modifications and differences
import mysql2 from "mysql2/promise"
import fs from "node:fs"
import jsyaml from "js-yaml"
import express from "express"
import knex from "knex"
const yaml = fs.readFileSync("./db.config.yaml", "utf8")
const config = jsyaml.load(yaml)
// const sql = await mysql2.createConnection({
// ...config.db
// })
const db = knex({
client: "mysql2",
connection: config.db,
})
const app = express()
app.use(express.json())
//查询接口 全部
app.get("/", async (req, res) => {
const data = await db("list").select().orderBy("id", "desc")
const total = await db("list").count("* as total")
res.json({
code: 200,
data,
total: total[0].total,
})
})
//单个查询 params
app.get("/user/:id", async (req, res) => {
const row = await db("list").select().where({ id: req.params.id })
res.json({
code: 200,
data: row,
})
})
//新增接口
app.post("/create", async (req, res) => {
const { name, age, hobby } = req.body
const detail = await db("list").insert({ name, age, hobby })
res.send({
code: 200,
data: detail,
})
})
//编辑
app.post("/update", async (req, res) => {
const { name, age, hobby, id } = req.body
const info = await db("list").update({ name, age, hobby }).where({ id })
res.json({
code: 200,
data: info,
})
})
//删除
app.post("/delete", async (req, res) => {
const info = await db("list").delete().where({ id: req.body.id })
res.json({
code: 200,
data: info,
})
})
const port = 3000
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Transaction
You can use transactions to ensure the atomicity of a set of database operations, that is, either all of them are successfully committed or all of them are rolled back
For example, A transfers money to B, which requires two statements. If statement A succeeds and statement B fails due to some scenarios, the money will be lost. Therefore, the transaction is to solve this problem, either succeed or roll back to ensure that the money will not be lost.
//伪代码
db.transaction(async (trx) => {
try {
await trx("list").update({ money: -100 }).where({ id: 1 }) //A
await trx("list").update({ money: +100 }).where({ id: 2 }) //B
await trx.commit() //提交事务
} catch (err) {
await trx.rollback() //回滚事务
}
})
Nodejs Chapter 40 (prisma)
What is prisma?
Prisma is a modern suite of database tools designed to simplify and improve the interaction between applications and databases. It provides a type-safe query builder and a powerful ORM (Object Relational Mapping) layer that enables developers to operate the database in a declarative manner.
Prisma supports a variety of major databases, including PostgreSQL, MySQL, and SQLite, by generating standard database models to interact with these databases. Using Prisma, developers can define database models and generate type-safe query builders that provide an intuitive set of methods for creating, updating, deleting, and querying data in a database.
Key features of Prisma include:
- Type-safe query builder: Prisma generates query builders using a strongly typed language such as TypeScript, providing the ability to catch errors and type checking at compile time. This helps reduce errors and provides a better developer experience.
- Powerful ORM layer: Prisma provides a powerful ORM layer that enables developers to operate the database in an object-oriented manner. It automatically generates the CRUD (create, read, update, delete) methods of the database model, simplifying interaction with the database.
- Database migration: Prisma provides database migration tools to help developers manage database schema changes. It can automatically create and apply migration scripts, making the database evolution process simpler and more controllable.
- Performance optimization: Prisma uses advanced query engine and data loading technology to improve the performance of database access. It supports advanced query features such as join queries and aggregation queries, and automatically optimizes queries to provide the best performance
Install and use
- Install Prisma CLI:
- Install using npm: run
npm install -g prisma. - Install using yarn: run
yarn global add prisma.
- Initialize project
- Use
prisma init --datasource-provider mysql
At this point, a basic directory will be created and generated.

- Connect to mysql
- Modify .env file
[DATABASE URL= "Mysql@account: password@host: port/poolname"] - Example
DATABASE_URL="mysql://root:123456@localhost:3306/xiaoman"
Create table
prisma/schema.prisma
model Post {
id Int @id @default(autoincrement()) //id 整数 自增
title String //title字符串类型
publish Boolean @default(false) //发布 布尔值默认false
author User @relation(fields: [authorId], references: [id]) //作者 关联用户表 关联关系 authorId 关联user表的id
authorId Int
}
model User {
id Int @id @default(autoincrement())
name String
email String @unique
posts Post[]
}
Execute command to create table
When using this command, be sure to pay attention to whether it covers all the contents in the current library. It is recommended to use a new library for testing.
prisma migrate dev

Implement addition, deletion, modification and query
import express from "express"
import { PrismaClient } from "@prisma/client"
const prisma = new PrismaClient()
const app = express()
const port: number = 3000
app.use(express.json())
//关联查找
app.get("/", async (req, res) => {
const data = await prisma.user.findMany({
include: {
posts: true,
},
})
res.send(data)
})
//单个查找
app.get("/user/:id", async (req, res) => {
const row = await prisma.user.findMany({
where: {
id: Number(req.params.id),
},
})
res.send(row)
})
//新增
app.post("/create", async (req, res) => {
const { name, email } = req.body
const data = await prisma.user.create({
data: {
name,
email,
posts: {
create: {
title: "标题",
publish: true,
},
},
},
})
res.send(data)
})
//更新
app.post("/update", async (req, res) => {
const { id, name, email } = req.body
const data = await prisma.user.update({
where: {
id: Number(id),
},
data: {
name,
email,
},
})
res.send(data)
})
//删除
app.post("/delete", async (req, res) => {
const { id } = req.body
await prisma.post.deleteMany({
where: {
authorId: Number(id),
},
})
const data = await prisma.user.delete({
where: {
id: Number(id),
},
})
res.send(data)
})
app.listen(port, () => {
console.log(`App listening on port ${port}`)
})
Nodejs Chapter 41 (Project Architecture MVC, IoC, DI)
So far, we have learned the express framework, writing interfaces, mysql database reading and writing data, knex, prisma ORM framework. Now it is time to put these together and implement an architecture similar to Nestjs or java's SpringBoot to truly develop our nodejs project
MVC
MVC (Model-View-Controller) is a commonly used software architecture pattern for designing and organizing application code. It divides the application into three main components: Model, View and Controller, each responsible for different responsibilities.
- Model: The model represents the data and business logic of the application. It is responsible for handling data storage, retrieval, verification and update operations. Models typically contain code that interacts with databases, file systems, or external services.
- View: The view is responsible for presenting the model data to the user in a visual form. It is responsible for the display of the user interface, including various graphic elements, page layout and user interaction components. Views are typically dynamically generated and updated based on the state of the model.
- Controller: The controller acts as the middleman between the model and the view, responsible for coordinating the interaction between the two. It receives user input (such as button clicks, form submissions, etc.) and updates the model's state or calls the corresponding model method based on the input. The controller can also update the view's display based on changes to the model.
The main goal of MVC is to separate an application's logic, data, and interface to improve code maintainability, scalability, and reusability. By assigning different responsibilities to different components, MVC provides a clear structure that enables developers to better manage and modify various parts of the application.
IoC Inversion of Control and DI Dependency Injection
Inversion of Control (IoC) and Dependency Injection (DI) are commonly used design patterns and techniques in software development for decoupling and managing dependencies between components. Although they are often used together, they are different concepts.
- Inversion of Control (IoC) is a design principle that transfers control of a component from the component itself to an external container. Traditionally, components are responsible for their own creation and management, but inversion of control transfers this responsibility to an external container or framework. The container is responsible for creating component instances and managing their life cycle. Components only need to declare the dependencies they need and obtain these dependencies through the container. This inversion of control makes components more loosely coupled, testable, and maintainable.
- Dependency injection (DI) is a specific technology to achieve inversion of control. It achieves loose coupling by moving a component's dependencies from inside the component to an external container. A component is no longer responsible for creating or managing other components on which it depends. Instead, dependencies are injected into the component through constructors, properties, or method parameters. Dependency injection can be achieved through constructor injection (Constructor Injection), property injection (Property Injection) or method injection (Method Injection).
Install dependencies
inversify+reflect-metadataimplements dependency injection official website- Interface writing
expressOfficial website - Connection tool
inversify-express-utilsDocument - orm framework
prismaofficial website - dto
class-validator+class-transformerDocument
Project structure
Create a new app folder
Build prisma project through prisma init --datasource-provider mysql As mentioned in the previous chapter
Directory structure
-
/src
-
/user
-
/controller.ts
-
/service.ts
-
/user.dto.ts
-
/post
-
/controller.ts
-
/service.ts
-
/post.dto.ts
-
/db
-
/index.ts
-
/prisma
-
/schema.prisma
-
main.ts
-
.env
-
tsconfig.json
-
package.json
-
README.md
Code writing
main.ts
import "reflect-metadata"
import { InversifyExpressServer } from "inversify-express-utils"
import { Container } from "inversify"
import { UserController } from "./src/user/controller"
import { UserService } from "./src/user/service"
import express from "express"
import { PrismaClient } from "@prisma/client"
import { PrismaDB } from "./src/db"
const container = new Container() //Ioc搞个容器
/**
* prisma依赖注入
*/
//注入工厂封装db
container.bind<PrismaClient>("PrismaClient").toFactory(() => {
return () => {
return new PrismaClient()
}
})
container.bind(PrismaDB).toSelf()
/**
* user模块
*/
container.bind(UserService).to(UserService) //添加到容器
container.bind(UserController).to(UserController) //添加到容器
/**
* post模块
*/
const server = new InversifyExpressServer(container) //返回server
//中间件编写在这儿
server.setConfig((app) => {
app.use(express.json()) //接受json
})
const app = server.build() //app就是express
app.listen(3000, () => {
console.log("http://localhost:3000")
})
src/user/controller.ts
import {
controller,
httpGet as GetMapping,
httpPost as PostMapping,
} from "inversify-express-utils"
import { inject } from "inversify"
import { UserService } from "./service"
import type { Request, Response } from "express"
@controller("/user") //路由
export class UserController {
constructor(
@inject(UserService) private readonly userService: UserService //依赖注入
) {}
@GetMapping("/index") //get请求
public async getIndex(req: Request, res: Response) {
console.log(req?.user.id)
const info = await this.userService.getUserInfo()
res.send(info)
}
@PostMapping("/create") //post请求
public async createUser(req: Request, res: Response) {
const user = await this.userService.createUser(req.body)
res.send(user)
}
}
src/user/service.ts
import { injectable, inject } from "inversify"
import { UserDto } from "./user.dto"
import { plainToClass } from "class-transformer" //dto验证
import { validate } from "class-validator" //dto验证
import { PrismaDB } from "../db"
@injectable()
export class UserService {
constructor(
@inject(PrismaDB) private readonly PrismaDB: PrismaDB //依赖注入
) {}
public async getUserInfo() {
return await this.PrismaDB.prisma.user.findMany()
}
public async createUser(data: UserDto) {
const user = plainToClass(UserDto, data)
const errors = await validate(user)
const dto = []
if (errors.length) {
errors.forEach((error) => {
Object.keys(error.constraints).forEach((key) => {
dto.push({
[error.property]: error.constraints[key],
})
})
})
return dto
} else {
const userInfo = await this.PrismaDB.prisma.user.create({ data: user })
return userInfo
}
}
}
src/user/user.dto.ts
import { IsNotEmpty, IsEmail } from "class-validator"
import { Transform } from "class-transformer"
export class UserDto {
@IsNotEmpty({ message: "用户名必填" })
@Transform((user) => user.value.trim())
name: string
@IsNotEmpty({ message: "邮箱必填" })
@IsEmail({}, { message: "邮箱格式不正确" })
@Transform((user) => user.value.trim())
email: string
}
src/db/index.ts
import { injectable, inject } from "inversify"
import { PrismaClient } from "@prisma/client"
@injectable()
export class PrismaDB {
prisma: PrismaClient
constructor(@inject("PrismaClient") PrismaClient: () => PrismaClient) {
this.prisma = PrismaClient()
}
}
tsconig.json
Support decorators and reflection. Turn on strict mode. Turn off strict mode.
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"strict": false,
Nodejs Chapter 42 (jwt)
What is jwt?
JWT (JSON Web Token) is an open standard (RFC 7519) used as a way to transfer information between web applications. It is a JSON-based security token used to transfer information between clients and servers. jwt.io/
A JWT consists of three parts, separated by dots (.):
- Header: Contains information such as the type of token and the encryption algorithm used. Usually represented by Base64 encoding.
- Payload: Contains authentication and authorization information, such as user ID, roles, permissions, etc. Other related information can also be customized. Also expressed using Base64 encoding.
- Signature: Sign the header and payload using the specified key to ensure the integrity and authenticity of the token.
The workflow of JWT is as follows:
- The user authenticates by providing valid credentials (such as username and password).
- The server verifies the credentials and generates a JWT in response. JWT contains the user's identity information and other necessary data.
- The server sends the JWT to the client.
- In subsequent requests, the client puts the JWT into the request header or other appropriate location.
- When the server receives the request, it verifies the signature of the JWT to ensure its integrity and authenticity. If the verification passes, the server uses the information in the JWT for authorization and authentication.
Dependencies used
passportpassport is a popular Node.js library for authentication and authorizationpassport-jwtPassport-JWT is a plug-in of the Passport library to support authentication and authorization using JSON Web Token (JWT)jsonwebtokenlibrary for generating tokens
Code writing
Use the code from the previous chapter to add the jwt directory Previous chapter code

src/jwt/index.ts
import { injectable } from "inversify"
import jsonwebtoken from "jsonwebtoken"
import passport from "passport"
import { Strategy, ExtractJwt } from "passport-jwt"
@injectable()
export class JWT {
private secret = "xiaoman$%^&*()asdsd"
private jwtOptions = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: this.secret,
}
constructor() {
this.strategy()
}
/**
* 初始化jwt
*/
public strategy() {
const strategy = new Strategy(this.jwtOptions, (payload, done) => {
done(null, payload)
})
passport.use(strategy)
}
/**
*
* @returns 中间件
*/
public middleware() {
return passport.authenticate("jwt", { session: false })
}
/**
* 创建token
* @param data Object
*/
public createToken(data: object) {
//有效期为7天
return jsonwebtoken.sign(data, this.secret, { expiresIn: "7d" })
}
/**
*
* @returns 集成到express
*/
public init() {
return passport.initialize()
}
}
main.ts
import "reflect-metadata"
import { InversifyExpressServer } from "inversify-express-utils"
import { Container } from "inversify"
import { User } from "./src/user/controller"
import { UserService } from "./src/user/services"
import express from "express"
import { PrismaClient } from "@prisma/client"
import { PrismaDB } from "./src/db"
import { JWT } from "./src/jwt"
const container = new Container()
/**
* user模块
*/
container.bind(User).to(User)
container.bind(UserService).to(UserService)
/**
* 封装PrismaClient
*/
container.bind<PrismaClient>("PrismaClient").toFactory(() => {
return () => {
return new PrismaClient()
}
})
container.bind(PrismaDB).to(PrismaDB)
/**
* jwt模块
*/
container.bind(JWT).to(JWT) //主要代码
const server = new InversifyExpressServer(container)
server.setConfig((app) => {
app.use(express.json())
app.use(container.get(JWT).init()) //主要代码
})
const app = server.build()
app.listen(3000, () => {
console.log("Listening on port 3000")
})
src/user/controller.ts
import {
controller,
httpGet as GetMapping,
httpPost as PostMapping,
} from "inversify-express-utils"
import { UserService } from "./services"
import { inject } from "inversify"
import type { Request, Response } from "express"
import { JWT } from "../jwt"
const { middleware } = new JWT()
@controller("/user")
export class User {
constructor(@inject(UserService) private readonly UserService: UserService) {}
@GetMapping("/index", middleware()) //主要代码
public async getIndex(req: Request, res: Response) {
let result = await this.UserService.getList()
res.send(result)
}
@PostMapping("/create")
public async createUser(req: Request, res: Response) {
let result = await this.UserService.createUser(req.body)
res.send(result)
}
}
src/user/services.ts
import { injectable, inject } from "inversify"
import { PrismaDB } from "../db"
import { UserDto } from "./user.dto"
import { plainToClass } from "class-transformer"
import { validate } from "class-validator"
import { JWT } from "../jwt"
@injectable()
export class UserService {
constructor(
@inject(PrismaDB) private readonly PrismaDB: PrismaDB,
@inject(JWT) private readonly jwt: JWT //依赖注入
) {}
public async getList() {
return await this.PrismaDB.prisma.user.findMany()
}
public async createUser(user: UserDto) {
let userDto = plainToClass(UserDto, user)
const errors = await validate(userDto)
if (errors.length) {
return errors
} else {
const result = await this.PrismaDB.prisma.user.create({
data: user,
})
return {
...result,
token: this.jwt.createToken(result), //生成token
}
}
}
}
Just add whichever interface requires token verification.
- Verification failure display (no token is carried)

- Successful verification display (with token)

Nodejs Chapter 43 (redis)
Redis (Remote Dictionary Server) is an open source in-memory data structure storage system. It provides an efficient key-value storage solution and supports a variety of data structures, such as Strings, Hashes, Lists, Sets and Sorted Sets. It is widely used in scenarios such as caching, message queues, and real-time statistics.
Here are some key features and uses:
- Memory storage: Redis mainly stores data in memory, so it has fast read and write performance. It can persist data to disk so that it can be restored after a reboot.
- Multiple data structures: Redis is not just a simple key-value store, it supports a variety of data structures, such as strings, hashes, lists, sets, and ordered sets. These data structures enable Redis to store and operate data more flexibly.
- Publish/Subscribe: Redis supports the publish/subscribe mode, allowing multiple clients to subscribe to one or more channels to receive real-time published messages. This allows Redis to be used as a real-time messaging system.
- Transaction support: Redis supports transactions, which can package multiple commands into one atomic operation for execution, ensuring that all commands are either executed successfully or fail.
- Persistence: Redis provides two ways to persist data: RDB (Redis Database) and AOF (Append Only File). RDB saves data to disk as a snapshot, while AOF appends each write operation to a file. These mechanisms ensure data durability across unexpected outages or restarts.
- High availability: Redis supports master-slave replication and Sentinel mechanism. Through master-slave replication, copies of multiple Redis instances can be created to improve read performance and fault tolerance. Sentinel is a system for monitoring and automatic failover, which can automatically promote a slave node to the master node if the master node goes down.
- Caching: Due to its fast read and write performance and flexible data structure, Redis is widely used as a caching layer. It can store commonly used data in memory to speed up data access and reduce the load on the back-end database.
- Real-time statistics: Redis’s data structures such as counters and ordered sets make it very suitable for real-time statistics scenarios. It can store and update counters, and perform ranking and range queries on ordered collections for statistical and leaderboard functions
redis installation
windows installation
- Installation package form
- Send me a private message to ask for the installation package

- Configure to environment variables

- Add to windows service (cmd administrator mode)
redis-server.exe --service-install [配置文件] --loglevel verbose
#例如
redis-server.exe --service-install redis.conf --loglevel verbose
- wsl installation
- redis.io/docs/instal…
- cmd administrator mode execute
wsl --updateto upgrade wsl versionwsl --set-default-version 2to set wsl version 2 - Open the Microsoft Store and search for wsl to install an Ubuntu


- Then follow the official website and execute the following commands

Mac,Linux installation
brew install redisStart redisredis-serverConnect redisredis-cliwget https://download.redis.io/redis-stable.tar.gz
Compile source files
tar -xzvf redis-stable.tar.gz
cd redis-stable
make
make install
Start redis
redis-server
Visualization tools
Open the Vscode extension and search for Database Client



Nodejs Chapter 44 (Basic use of redis)
String operations
SET key value [NX|XX] [EX seconds] [PX milliseconds] [GET]
key: The key name to be set.value: The value to be set.NX: Optional parameter, indicating that the value is only set when the key does not exist.XX: Optional parameter, indicating that the value will only be set when the key already exists.EX seconds: Optional parameter, sets the expiration time of the key to the specified number of seconds.PX milliseconds: Optional parameter, sets the expiration time of the key to the specified number of milliseconds.GET: Optional parameter, returns the old value of the key.
- Set the value of the key name "name" to "John":
SET name "xiaoman"
- Set the value of the key name "counter" to 10, and set the expiration time to 60 seconds:
SET counter 10 EX 60
- Only when the key name "status" does not exist, set its value to "active":
SET status "active" NX
- Only if the key name "score" already exists, increase its value by 5:
SET score 5 XX
- Set the value of the key named "message" to "Hello" and return the old value:
SET message "Hello" GET
- Delete the key named "name":
DEL name
- Delete multiple key names in batches:
DEL key1 key2 key3
- Delete non-existing key names without reporting an error, and return the number of deleted keys as 0:
DEL non_existing_key

Collection operations
A set is an unordered and non-repeating data structure used to store a set of independent elements. There is no clear order relationship between the elements in the set, and each element can only appear once in the set.
- Add members to the collection:
SADD fruits "apple"
SADD fruits "banana"
SADD fruits "orange"
- Get all members in the collection:
SMEMBERS fruits
Output result:
1) "apple"
2) "banana"
3) "orange"
- Check whether the member exists in the collection:
SISMEMBER fruits "apple"
Output result:
(integer) 1
- Remove members from the collection:
SREM fruits "banana"
Output result:
(integer) 1
- Get the number of members in the set:
SCARD fruits
Output result:
(integer) 2
- Get random members:
SRANDMEMBER fruits
Output result:
"apple"
- Find the union of multiple sets:
SUNION fruits vegetables
Output result:
1) "apple"
2) "orange"
3) "tomato"
4) "carrot"
- Find the intersection of multiple sets:
SINTER fruits vegetables
Output result:
"apple"
- Find the difference of multiple sets:
SDIFF fruits vegetables
Output result:
"orange"
Hash table operation
A hash table (Hash) is a data structure, also known as a dictionary, associative array, or map, used to store a collection of key-value pairs. In a hash table, keys and values are stored data items, and the keys are mapped to specific storage locations through a hash function, enabling fast data access and lookup.
- Set the field value in the hash table:
HSET obj name "John"
HSET obj age 25
HSET obj email "john@example.com"
- Get the field value in the hash table:
HGET obj name
Output result:
"John"
- Set the values of multiple fields at once:
HMSET obj name "John" age 25 email "john@example.com"
- Get the values of multiple fields:
HMGET obj name age email
Output result:
1) "John"
2) "25"
3) "john@example.com"
- Get all fields and values in the hash table:
HGETALL obj
Output result:
1) "name"
2) "John"
3) "age"
4) "25"
5) "email"
6) "john@example.com"
- Delete fields in the hash table:
HDEL obj age email
Output result:
(integer) 2
- Check whether the specified field exists in the hash table:
HEXISTS obj name
Output result:
(integer) 1
- Get all fields in the hash table:
HKEYS obj
Output result:
1) "name"
- Get all values in the hash table:
HVALS obj
Output result:
1) "John"
- Get the number of fields in the hash table:
HLEN obj
Output result:
(integer) 1
List operations
List is an ordered, mutable and repeatable data structure. A list is a common type of data structure used in many programming languages and data storage systems to store a set of elements.
- Add elements:
RPUSH key element1 element2 element3 // 将元素从右侧插入列表
LPUSH key element1 element2 element3 // 将元素从左侧插入列表
LPUSH key element1 element2 ...: Insert one or more elements from the left side of the list, that is, insert the elements intoHeadof the list in sequence. If the list does not exist, a new list will be automatically created before performing the operation.RPUSH key element1 element2 ...: Insert one or more elements from the right side of the list, that is, insert the elements intoEndof the list in sequence. If the list does not exist, a new list will be automatically created before performing the operation.
- Get elements:
LINDEX key index // 获取列表中指定索引位置的元素
LRANGE key start stop // 获取列表中指定范围内的元素
- Modify elements:
LSET key index newValue // 修改列表中指定索引位置的元素的值
- Delete elements:
LPOP key // 从列表的左侧移除并返回第一个元素
RPOP key // 从列表的右侧移除并返回最后一个元素
LREM key count value // 从列表中删除指定数量的指定值元素
- Get the list length:
LLEN key // 获取列表的长度
Nodejs Chapter 45 (redis publish and subscribe + transaction)
Publish and subscribe
Publish-subscribe is a messaging pattern in which a message publisher (publisher) sends messages to a channel (channel), and subscribers (subscribers) can subscribe to one or more channels to receive messages. This model allows the decoupling of messages, and publishers and subscribers can operate independently without direct interaction.
In Redis, publish-subscribe mode operates with the following command:
- PUBLISH command: used to publish messages to the specified channel. The syntax is: PUBLISH channel message. For example, PUBLISH news "Hello, world!" publishes the message "Hello, world!" to the channel named "news".
- SUBSCRIBE command: used to subscribe to one or more channels. The syntax is: SUBSCRIBE channel [channel ...]. For example, SUBSCRIBE news sports subscribes to channels named "news" and "sports".
- UNSUBSCRIBE command: used to unsubscribe one or more channels. The syntax is: UNSUBSCRIBE [channel [channel ...]]. For example, UNSUBSCRIBE news unsubscribes from the channel named "news".
- PSUBSCRIBE command: used to pattern subscribe to one or more matching channels. The syntax is: PSUBSCRIBE pattern [pattern ...]. Among them, pattern can contain wildcard characters. For example, PSUBSCRIBE news.* subscribes to all channels starting with "news.".
- PUNSUBSCRIBE command: used to cancel pattern subscription to one or more matching channels. The syntax is: PUNSUBSCRIBE [pattern [pattern ...]]. For example, PUNSUBSCRIBE news.* unsubscribes all channels starting with "news.".

Transaction
Redis supports transactions, which allows users to package multiple commands together for execution as a unit. Transactions provide a mechanism for atomic operations. Either all commands are executed successfully, or all commands are not executed.
Redis transactions are managed using commands such as MULTI, EXEC, WATCH and DISCARD.
- MULTI command: used to start a transaction. After executing the MULTI command, Redis will add all subsequent commands to the transaction queue instead of executing them immediately.
- EXEC command: used to execute all commands in the transaction. When executing the EXEC command, Redis will execute all commands in the order in the transaction queue. The execution results are returned to the client in the form of an array.
- WATCH command: used to monitor one or more keys. If the monitored key is modified before the transaction is executed, the transaction will be interrupted and will not be executed.
- DISCARD command: used to cancel transactions. When the DISCARD command is executed, all commands in the transaction queue will be cleared and the transaction will be cancelled.
The basic process of using transactions is as follows:
- Use the MULTI command to start a transaction.
- Add the commands to be executed to the transaction queue.
- If necessary, use the WATCH command to watch the keys.
- Execute the EXEC command to execute the transaction. Redis will execute the commands in the order in the queue and return the execution results.
- Determine whether the transaction execution is successful based on the returned result.
The commands in the transaction are not executed immediately before execution, but are executed when the EXEC command is executed. This means that commands during a transaction will not block other clients' operations, nor will they interrupt other clients' read and write operations on keys.
It should be noted that Redis does not support rollback operations. If an error occurs during transaction execution, the transaction continues without rolling back executed commands. Therefore, when using Redis transactions, you need to ensure that the commands in the transaction are idempotent, that is, the result of executing the command multiple times is the same as the result of executing it once.
# 连接Redis
redis-cli
# 开启事务
MULTI
# 添加命令到事务队列
SET key1 value1
GET key2
# 执行事务
EXEC

Nodejs Chapter 46 (redis persistence)
redis persistence
Redis provides two persistence methods:
- RDB (Redis Database) persistence: RDB is a form of snapshot, which regularly saves data in memory to disk. You can configure the Redis server to set conditions for automatically triggering RDB snapshots, such as saving snapshots within a specified time interval or when the number of specified write operations reaches a certain threshold. The snapshot file generated by RDB persistence is a binary file that contains the complete status of Redis data. When restoring data, the data can be reloaded into memory by loading the snapshot file.
- AOF (Append-Only File) persistence: AOF persistence records all write operation commands executed by the Redis server and saves them in the file in an appended manner. When Redis needs to be restarted, the commands saved in the AOF file can be re-executed to reconstruct the data set. Compared to RDB persistence, AOF persistence provides better data recovery guarantees because it records each write operation rather than in the form of a snapshot. However, AOF files are larger than RDB files, and data recovery may be slower.
RDB usage
Open the redis configuration file

find save

He provided three cases
- A snapshot will be triggered if a change is made within 3600 seconds, that is, once an hour.
- Within 300 seconds, which is 5 minutes, a snapshot will be taken if 100 modifications are made.
- A snapshot will be taken after 10,000 modifications within 60 seconds.
The specific scenario needs to be defined based on your user volume and load conditions.

Secondly, you can manually trigger the snapshot through the command line.

AOF usage
- Set the value of the
appendonlyconfiguration item toyes: By default, the value of this configuration item isno, indicating that AOF persistence is not enabled. Modify its value toyesto enable AOF persistence.

Nodejs Chapter 47 (redis master-slave replication)
Redis master-slave replication is a data replication and synchronization mechanism in which one Redis server (called the master server) replicates its data to one or more other Redis servers (called slave servers). Master-slave replication provides functions such as data redundancy backup, read-write separation, and fault recovery.

The following is the general workflow of Redis master-slave replication:
- Configure the master server: On the master server, you need to enable master-slave replication in the configuration file and specify the IP address and port number of the slave server. You can use the
replicaofconfiguration option or theslaveofconfiguration option to specify a slave server. - Connect to the slave server: The slave server connects to the master server and sends a replication request. The slave server requests full copy by sending the
SYNCcommand or partial copy (incremental copy) by sending thePSYNCcommand. - Full replication (SYNC): If the slave server is connected for the first time or cannot perform partial replication, the master server will perform full replication. During full replication, the master server sends a snapshot file (RDB file) to the slave server, which receives and loads the file to fully replicate the master server's data.
- Partial replication (PSYNC): If the slave server has performed full replication and established a replication breakpoint, the master server will perform partial replication. During partial replication, the master server will send an incremental replication stream to the slave server, and the slave server will receive and apply the stream to stay in sync with the master server.
- Replication persistence: After receiving data from the server, it will be saved on the local disk to maintain data consistency after restarting.
- Synchronization delay: Replication from the slave server is asynchronous, so there is a replication delay. Latency depends on factors such as network latency, the load on the master server, and the performance of the slave servers.
- Read and write separation: Once the master-slave replication relationship is established, the slave server can receive read operations. This makes it possible to spread read traffic from the master server to the slave servers, thereby reducing the load on the master server.
- Failure recovery: If the master server fails, a slave server can be promoted to the new master server to continue providing services. When the master server recovers, it can connect to the new master server as a slave server and continue data replication.
Modify configuration file
Create a new redis-6378.conf configuration file under the root directory as redisFrom Server, and the default configuration file 6379 as Main server
redis-6378.conf file configuration
bind 127.0.0.1 #ip地址
port 6378 #端口号
daemonize yes #守护线程静默运行
replicaof 127.0.0.1 6379 #指定主服务器
Start the slave server
redis-server ./redis-6378.conf 指定配置文件
Open the slave server cli
redis-cli -p 6378
Start the main server
redis-cli 直接启动默认就是主服务器的配置文件
The master writes a value
set master 2
This value can be obtained directly by synchronizing it directly from the server.
Note that writing operations are not allowed from the server

Nodejs Chapter 48 (ioredis)
ioredis is a powerful and popular Node.js library for interacting with Redis. Redis is an open source in-memory data structure storage system. ioredis provides a simple and efficient API for Node.js applications to communicate with Redis servers.
Here are some of the main features of ioredis:
- High performance: ioredis is designed to be fast and efficient. It supports pipeline operations to send multiple Redis commands in a single round trip, thereby reducing network latency. It also supports connection pooling and can automatically reconnect to the Redis server if the connection is lost.
- Promises and async/await support: ioredis uses promises and supports async/await syntax, making writing asynchronous code and processing Redis commands more readable.
- Clustering and sentinel support: ioredis has built-in support for Redis clustering and Redis Sentinel, which are advanced features of Redis for distributed setups and high availability. It provides an intuitive API for handling Redis clusters and failover scenarios.
- Lua script: ioredis allows you to use the
evalandevalshacommands to execute Lua scripts on the Redis server. This feature allows you to perform complex operations on the server side, reducing the number of round trips between the client and the server. - Publish/subscribe and blocking commands: ioredis supports Redis’ publish/subscribe mechanism, allowing you to create real-time messaging systems and event-driven architectures. It also provides support for blocking commands such as
BRPOPandBLPOP, allowing you to wait for items to be pushed to the list and pop them atomically. - Streams and pipelines: ioredis supports Redis’ stream data type, allowing you to consume and generate data streams. It also provides a convenient way to pipeline multiple commands, reducing the number of round trips to the server.
How to use
Installation
npm i ioredis
Connect redis
import Ioredis from "ioredis"
const ioredis = new Ioredis({
host: "127.0.0.1", //ip
port: 6379, //端口
})
- String
//存储字符串并且设置过期时间
ioredis.setex("key", 10, "value")
//普通存储
ioredis.set("key", "value")
//读取
ioredis.get("key")
- Collection
// 添加元素到集合
redis.sadd("myset", "element1", "element2", "element3")
// 从集合中移除元素
redis.srem("myset", "element2")
// 检查元素是否存在于集合中
redis.sismember("myset", "element1").then((result) => {
console.log("Is member:", result) // true
})
// 获取集合中的所有元素
redis.smembers("myset").then((members) => {
console.log("Members:", members)
})
- Hash
// 设置哈希字段的值
redis.hset("myhash", "field1", "value1")
redis.hset("myhash", "field2", "value2")
// 获取哈希字段的值
redis.hget("myhash", "field1").then((value) => {
console.log("Value:", value) // "value1"
})
// 删除哈希字段
redis.hdel("myhash", "field2")
// 获取整个哈希对象
redis.hgetall("myhash").then((hash) => {
console.log("Hash:", hash) // { field1: 'value1' }
})
- Queue
// 在队列的头部添加元素
redis.lpush("myqueue", "element1")
redis.lpush("myqueue", "element2")
// 获取队列中所有元素
redis.lrange("myqueue", 0, -1).then((elements) => {
console.log("Queue elements:", elements)
})
//获取长度
redis.llen("myqueue").then((length) => {
console.log("Queue length:", length)
})
Publish and subscribe
// 引入 ioredis 库
import Ioredis from "ioredis"
// 创建与 Redis 服务器的连接
const ioredis = new Ioredis({
host: "127.0.0.1",
port: 6379,
})
// 创建另一个 Redis 连接实例
const redis2 = new Ioredis()
// 订阅频道 'channel'
ioredis.subscribe("channel")
// 监听消息事件
ioredis.on("message", (channel, message) => {
console.log(`Received a message from channel ${channel}: ${message}`)
})
// 发布消息到频道 'channel'
redis2.publish("channel", "hello world")
Nodejs Chapter 49 (lua)
lua
Lua is a lightweight, efficient, embeddable scripting language originally developed by a small team at the Pontifical Catholic University of Rio de Janeiro, Brazil. Its name "Lua" means "moon" in Portuguese, implying Lua as a bright language.
Lua has concise syntax and flexible semantics, and is widely used in embedded systems, game development, Web applications, scripting and other fields. One of its design goals is to serve as an extension and embedded scripting language that can be seamlessly integrated with other programming languages. Lua's core has a small code base, but its functionality can be easily extended through the use of modules and libraries.
Here are some key features and uses:
- Concise and efficient: Lua’s syntax is simple and clear, and its semantics are flexible and efficient. It uses dynamic typing and automatic memory management, supports procedural and functional programming styles, and provides powerful coroutine support.
- Embedded scripting language: Lua is designed as an embeddable scripting language that can be easily integrated with other programming languages. It provides a C API that allows developers to embed Lua into C/C++ programs or embed Lua into other applications through extension libraries.
- Game development: Lua is widely used in game development. Many game engines (such as Unity and Corona SDK) support Lua as a scripting language. Developers can use Lua to write game logic, scene management, AI, etc.
- Scripting: Lua is often used as a scripting language due to its simplicity and ease of learning. It can be used for writing various system tools, automating tasks and rapid prototyping.
- Configuration files: Lua's syntax is very suitable for use as a configuration file format. Many applications and frameworks use Lua as their configuration file language because it is easy to read, write, and modify.
For enhanced performance and scalability, Lua can be used with Redis and Nginx. This combination can be used to build high-performance web applications or API services.
- Redis: Redis is a fast and efficient in-memory data storage system that supports various data structures such as strings, hashes, lists, sets, and ordered sets. Combined with Lua, you can take advantage of the caching capabilities of Redis and the flexibility of Lua to handle some complex calculations or data queries.
- Cache data: Using Redis as cache storage, frequently accessed data can be stored in Redis to reduce the load on the back-end database. Lua can write scripts that interact with Redis to increase data access speed by reading and writing Redis data.
- Distributed lock: Through the atomic operation of Redis and the scripting capability of Lua, a distributed lock mechanism can be implemented to solve the problems of concurrent access and resource competition.
- Nginx: Nginx is a high-performance web server and reverse proxy server. It supports the use of Lua embedded modules to extend its functionality.
- Request processing: Using Nginx's Lua module, Lua scripts can be written to handle HTTP requests. This allows some pre-processing, authentication, request routing, etc. to be done before the request reaches the application server, thus reducing the load on the backend server.
- Dynamic response: By combining the subrequest mechanism of Lua and Nginx, dynamic response generation can be achieved. This is useful for generating dynamic content based on request parameters or other conditions.
- Access control: Using Lua scripts, you can perform fine-grained control on access at the Nginx level, such as IP whitelists, blacklists, request frequency limits, etc.
Installation



Just choose the corresponding platform and download it.

Once the download is complete, configure the environment variables.

Use lua54 to test it

vscode support
Find the extension and install the following two plug-ins

debug code

Nodejs Chapter 50 (Basic use of lua)

Basic use of lua
global variables local variables
- Global variables are variables defined in the global scope and can be accessed anywhere in the script.
- Global variables do not need to use keywords when defining, just assign values directly.
xiaoman = 'xmzs'
print(xiaoman)
- Local variables are variables defined within a specific scope and can only be accessed within the scope to which they belong.
- The scope of local variables is usually inside the function body, but local variables can also be created in code blocks (using
do...end). - In local scope, local variables can be defined through simple assignment statements.
--local 定义局部变量
local xiaoman = 'xmzs'
print(xiaoman)
conditional statement
In Lua, conditional judgment statements can be implemented using the if, elseif and else keywords
local xiaoman = 'xmzs'
if xiaoman == "xmzs" then
print("xiaoman")
elseif xiaoman == "xmzs1" then
print("xiaoman1")
else
print("not xiaoman")
end
function
In Lua, a function is a reusable block of code that performs a specific task or operation
local xiaoman = 'xmzs'
function func(name)
if name == "xmzs" then
print("xiaoman")
return 1
elseif name == "xmzs1" then
print("xiaoman1")
return 2
else
print("not xiaoman")
return 3
end
end
local result = func(xiaoman)
print(result)
Data type
nil: Indicates invalid value or missing value.boolean: represents a Boolean value, which can betrueorfalse.number: represents numbers, including integers and floating point numbers.string: represents a string, consisting of a character sequence.table: represents a table, an associative array used to store and organize data.function: represents a function, used to encapsulate executable code blocks.userdata: Represents user-defined data type, usually used interactively with C language library.thread: represents coroutine, used to implement multi-thread programming.metatable: Represents a metatable, used to define the behavior of the table.
Common data type usage
type = false --布尔值
type = nil --就是null
type = 1 --整数
type = 1.1 --浮点型
type = 'xmzs' --字符串
print(type)
String concatenation ..
local s = 'xm'
local m = 'zs'
print(s .. m)
table can describe objects and arrays
lua index starts from 1
--对象
table = {
name = "xiaoman",
age = 18
}
print(table.name)
print(table.age)
--数组
arr = {1,2,3,4,6}
print(arr[1])
loop
for i = 1, 10, 3 do --开始 结束 步长 步长就是递增数量
print(i)
end
Loop table
arr = {name = "hello", age = 18, sex = "male"}
for k, v in pairs(arr) do
print(k, v) --key 和 value 也就是 name 和 hello ...
end
loop array
local arr = {10,20,30}
for i, v in ipairs(arr) do
print(i,v)
end
Modularity
test.lua exposes a method add
local M = {}
function M.add(a, b)
return a + b
end
return M
index.lua introduces the file and calls the add method
local math = require('test')
local r = math.add(1, 2)
print(r)
Nodejs Chapter 51 (Limiting Valve)
Current limiting function
At present, we have learned redis, lua, and nodejs, so we can combine them to make a current limiting function, like a lottery function. If you click too many times, you will be prompted to try again later to limit it. Let's implement this function.
Install dependencies
npm i ioredis express
Code writing
index.js
- express helps us provide interfaces -ioredis can run lua scripts and connect to the redis service
- We made three constants. The first TIME is to control the operation within a time, such as 30 seconds. The second CHANGE is to control the number of operations, such as five operations. The third one is key, which is the value stored in redis and defines three constants of the current limiting valve.
- redis.eval The first parameter is the Lua code and we read it using fs. The second parameter is the number of keys. We have 1. The third parameter is the key. The fourth parameter is the arguments. The fifth parameter is also the arguments. The sixth parameter is a failed callback. Success will accept the return value.
import express from "express"
import Redis from "ioredis"
import fs from "node:fs"
const lua = fs.readFileSync("./index.lua", "utf8")
const redis = new Redis()
const app = express()
//限流阀
const TIME = 30
const CHANGE = 5
const KEY = "lottery"
app.use("*", (req, res, next) => {
res.header("Access-Control-Allow-Origin", "*")
next()
})
app.get("/lottery", (req, res) => {
//lua 就是lua的脚本
//1 代表有一个key
//key就是接受的key
//TIME 是 第一个参数
//CHANGE 是 第二个参数
redis.eval(lua, 1, KEY, CHANGE, TIME, (err, result) => {
if (err) {
console.log(err)
}
if (result === 1) {
res.send("抽奖成功")
} else {
res.send("请稍后重试!")
}
})
})
app.listen(3000, () => {
console.log("Server started on port 3000")
})
index.lua
KEYS | ARGV global variables can only be used in redis- tonumber is to convert a string to a numeric type
- redis.call is the command to call redis
- incr is the increment value
- expire is the storage expiration time
- The general idea is to read the value first. If the value exists and exceeds the current limiting valve, 0 will be returned to indicate frequent operations. Otherwise, click once and accumulate once.
local key = KEYS[1] --接受key值
local limit = tonumber(ARGV[1])
local interval = tonumber(ARGV[2])
local count = tonumber(redis.call("get", key) or "0")
if count > limit then
return 0
else
redis.call("incr", key) -- lottery: 0++ 1 2 3 4 5
redis.call("expire", key, interval) -- lottery: 0 1 2 3 4 5
return 1
end
index.html code test
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button id="btn">抽奖</button>
<script>
const btn = document.getElementById("btn")
btn.onclick = function () {
fetch("http://localhost:3000/lottery")
.then((res) => {
return res.text()
})
.then((data) => {
console.log(data)
alert(data)
})
}
</script>
</body>
</html>
more than five times

Normal click

Nodejs Chapter 52 (Timed Tasks)
What is a scheduled task?
A scheduled task refers to a task or operation that is performed at a predetermined time point or interval. They are a way to automate specific logic and can be used to perform repetitive, periodic or scheduled tasks.
Scheduled tasks are usually used in the following situations:
- Execute background tasks: Scheduled tasks can be used to automatically perform background tasks, such as data backup, log cleaning, cache refresh, etc. By setting appropriate time points or intervals, you can ensure that these tasks proceed as planned without manual intervention.
- Perform regular operations: Scheduled tasks can be used to perform regular operations, such as sending email reminders, generating reports, updating data, etc. By setting appropriate time points, these operations can be triggered automatically, improving efficiency and reducing the need for manual operations.
- Scheduling tasks and workflows: Scheduled tasks can be used to schedule and coordinate complex tasks and workflows. By setting dependencies between tasks and executing
Install dependencies
npm install node-schedule
Generally, scheduled tasks use
cronexpression to express time.
cron expression
Cron expression is a string representation used to specify the execution time of a scheduled task. It consists of 6 or 7 fields, each field represents the time unit and scope of task execution.
The typical format of a Cron expression is as follows:
---
┬ ┬ ┬ ┬ ┬ ┬
│ │ │ │ │ │
│ │ │ │ │ └── 星期(0 - 6,0表示星期日)
│ │ │ │ └───── 月份(1 - 12)
│ │ │ └────────── 日(1 - 31)
│ │ └─────────────── 小时(0 - 23)
│ └──────────────────── 分钟(0 - 59)
└───────────────────────── 秒(0 - 59)
| Domain | Required | Value range | Special characters |
|---|---|---|---|
| Seconds Seconds | Yes | [0, 59] | * , - / |
| Minutes | Yes | [0, 59] | * , - / |
| Hours | Yes | [0, 23] | * , - / |
| Date DayofMonth | Yes | [1, 31] | * , - / ? L W |
| Month Month | Yes | [1, 12] or [JAN, DEC] | *, - / |
| DayofWeek | Is | [1, 7] or [MON, SUN]. If the expression [1, 7] is used, 1 represents Monday and 7 represents Sunday. | * , - / ? L # |
| Year Year | No | 1970+ | - * / |
Each field can accept specific values, ranges, wildcards, and special characters to specify the execution time of the task:
- Numeric value: represents a specific time unit, such as 1, 2, 10, etc.
- Range: Use
-to connect the starting and ending values to represent all values within a range, such as 1-5 representing all values from 1 to 5. - Wildcard: Use
*to represent all possible values that match the field, such as*to represent every minute, every hour, every day, etc. - Comma separation: Use commas to separate multiple values or ranges, which means matching any one of the values, such as 1,3 means 1 or 3.
- Step size: Use
/to represent the step size, which is used to specify the interval value. For example,*/5means to execute every 5 units. - Special characters: Cron expressions also support some special characters to express specific meanings, such as
?for replacing any value in the day and week fields,Lfor the last day,Wfor the latest working day, etc.
Here are some common Cron expression examples:
* * * * * *: Execute the task once per second.0 * * * * *: Execute the task on the hour every minute.0 0 * * * *: Execute the task once every hour on the hour.0 0 * * 1 *: Execute the task every Monday at midnight.0 0 1 * * *: Execute the task at midnight on the 1st of every month.0 0 1 1 * *: A mission is performed every year at midnight on January 1st.
Code writing (Nuggets automatic sign-in)
import schedule from "node-schedule"
import request from "request"
import config from "./config.js"
schedule.scheduleJob("0 30 0 * * *", () => {
request(
config.check_url,
{
method: "post",
headers: {
Referer: config.url,
Cookie: config.cookie,
},
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
}
)
})
config.js
export default {
cookie: "sessionid=你的cookie",
url: "https://juejin.cn/",
check_url:
"https://api.juejin.cn/growth_api/v1/check_in?aid=你的aid&uid=你的uid",
}

aid uid cookie
Just go to any interface and look for aid and uid.

cookie

Nodejs Chapter 53 (serverLess)
What is serverLess?
Serverless is not a technology but an architectural model. In a traditional deployment, you must choose a server operating system such as Linux or Windows, install and configure the environment, understand operating-system commands, and manage security. Serverless architecture lets developers focus on the business instead of server operations.
FaaS and BaaS
- Function as a Service (FaaS):
FaaS is a serverless computing model that allows developers to write and deploy functional code without caring about underlying server management. In FaaS, developers only need to focus on the implementation and logic of the function and upload it to the cloud platform, and the platform will be responsible for the running and expansion of the function. When a request triggers a function, the cloud platform will automatically provide the required computing resources for the function and elastically expand based on the amount of requests. This on-demand computing model allows developers to focus more on the implementation of business logic while achieving efficient use of resources.
Each function is a service. You only need to process business within the function. You can use the services provided by the BASS layer to complete the business without worrying about the computing resources behind it.
- Backend as a Service (BaaS):
Backend as a Service is a cloud service model that provides backend functions for mobile applications and web applications. BaaS provides developers with a set of pre-built backend services such as user authentication, database storage, file storage, push notifications, etc. to simplify application development and management. Developers can use the API and SDK provided by the BaaS platform to directly integrate these functions into their applications without having to build and maintain back-end infrastructure themselves.
Treat back-end resources as a service, such as file storage, data storage, push services, and identity authentication. This layer only needs to provide corresponding services and does not need to care about business. It is defined as the underlying basic service, which is called by other services and does not normally touch the user terminal.
Write a Serverless Cloud Function
Install dependencies
npm install @serverless-devs/s -g
Serverless Devs is an open source and open Serverless developer platform dedicated to providing developers with a powerful tool chain system. Through this platform, developers can not only experience multi-cloud Serverless products with one click and quickly deploy Serverless projects, but also manage projects throughout the entire life cycle of Serverless applications, and combine Serverless Devs with other tools/platforms very simply and quickly to further improve R&D and operation and maintenance efficiency.
- Configure the key
We need to choose a cloud product. Here I use Alibaba Cloud for demonstration. Of course, you can also use other cloud products. Personally, I feel that Alibaba Cloud is easy to use.
Visit the link below to log in to Alibaba Cloud
ram.console.aliyun.com/manage/ak

- Add key
s command. After you complete the installation, @serverless-devs/s will be available.
s config add

Select Alibaba Cloud and enter the AccessKeyID AccessKeySecret. The third alias can be customized.

Check whether the key is correct. If the information can be output, it is correct.
s config get -a [别名]

- Create a project
Just run the s command directly
s

Open the generated project

Execute in directory
s deploy
Upload successful

fcnext.console.aliyun.com/cn-beijing/…
Visit this link to find your function


call this function


Nodejs Chapter 54 (net)
The net module is one of the core modules of Node.js, which provides an API for creating web-based applications. The net module is mainly used to create TCP servers and TCP clients, as well as handle network communications.

TCP (Transmission Control Protocol) is a connection-oriented, reliable transmission protocol used for data transmission on computer networks. It is part of the Internet Protocol suite (TCP/IP) and is the transport layer protocol between the application layer and the network layer.
The main features of TCP include:
- Reliability: TCP ensures reliable transmission of data by using acknowledgment mechanisms, sequence numbers, and retransmission strategies. It detects and corrects problems with missing, duplicate, corrupted or out-of-order data.
- Connection-oriented: Before data transmission, TCP needs to establish a connection between the sender and the receiver. The connection is established through a three-way handshake, ensuring that both parties are ready to communicate.
- Full-duplex communication: TCP supports two-way communication between both parties at the same time, that is, the sender and receiver can send and receive data at the same time.
- Streaming transmission: TCP transmits data as a continuous stream of bytes rather than discrete data packets. The sender divides the data into smaller chunks, but TCP handles it as a continuous stream of bytes during transmission.
- Congestion control: TCP has a congestion control mechanism to avoid network congestion and data loss. It controls the data sending speed by dynamically adjusting the sending rate, using congestion windows and slow start algorithms.
Scene
- Communication between servers
Communication between servers can directly use TCP communication without going up to the http layer.
server.js
Create a TCP service and send a socket listening on port number 3000
import net from "net"
const server = net.createServer((socket) => {
setInterval(() => {
socket.write("XiaoMan")
}, 1000)
})
server.listen(3000, () => {
console.log("listening on 3000")
})
client.js
Connect to the server and monitor the returned data
import net from "net"
const client = net.createConnection({
host: "127.0.0.1",
port: 3000,
})
client.on("data", (data) => {
console.log(data.toString())
})
- Implement http protocol from the transport layer
Create a TCP service
import net from "net"
const http = net.createServer((socket) => {
socket.on("data", (data) => {
console.log(data.toString())
})
})
http.listen(3000, () => {
console.log("listening on 3000")
})
net.createServer creates the Unix domain socket and returns a server object that accepts a callback function
socket can monitor many events
closetriggers once the socket is completely closedconnectTriggered when the socket connection is successfully establisheddatatriggers when data is receivedendtriggers when the other end of the socket indicates the end of the transmission, thus ending the readable end of the socket
After starting through node http.js, we use the browser to access it

You can see that the browser sent an http get request. We can return relevant content through the keyword get, such as html
import net from "net"
const html = `<h1>TCP Server</h1>`
const reposneHeader = [
"HTTP/1.1 200 OK",
"Content-Type: text/html",
"Content-Length: " + html.length,
"Server: Nodejs",
"\r\n",
html,
]
const http = net.createServer((socket) => {
socket.on("data", (data) => {
if (/GET/.test(data.toString())) {
socket.write(reposneHeader.join("\r\n"))
socket.end()
}
})
})
http.listen(3000, () => {
console.log("listening on 3000")
})

Nodejs Chapter 55 (socket.io)
Traditional HTTP is a one-way request-response protocol. After the client sends a request, the server will respond and return the corresponding data. In traditional HTTP, the client needs to actively send a request to obtain resources on the server, and each request needs to re-establish the connection. This method is inefficient in real-time communication and continuous resource acquisition scenarios.

Socket provides real-time two-way communication capabilities and can transmit data in real time. The communication between the client and the server is instant, and the transmission and response of data are completed almost in real time, without the need for polling or timing requests.

Install dependencies
In normal development, we will use mature third-party libraries, the native websocket, which is used less frequently and can be used in some simple projects or some ordinary businesses, but most of them still use third-party libraries.
socket.io
Socket.IO is an event-driven real-time communication framework for building real-time applications. It provides two-way, low-latency communication capabilities so that the server and client can send and receive data in real time.
Key features of Socket.IO include:
- Real-time: Socket.IO is built on the WebSocket protocol and uses WebSocket connections to achieve real-time communication. WebSocket is a two-way communication protocol that enables faster, lower-latency data transfer than the traditional HTTP request-response model.
- Event-driven: Socket.IO uses an event-driven programming model. Servers and clients can send and receive data by triggering events. This event-based communication model allows developers to easily build real-time applications, such as chat applications, real-time collaboration tools, etc.
- Cross-platform support: Socket.IO can be used on multiple platforms, including browsers, servers, and mobile devices. It provides support for multiple programming languages and frameworks, such as JavaScript, Node.js, Python, Java, etc., allowing developers to build real-time applications in different environments.
- Fault Tolerance: Socket.IO is fault tolerant and can automatically downgrade to other transport mechanisms such as HTTP long polling when the WebSocket connection is unavailable. This means that Socket.IO can still enable real-time communication even in environments that do not support WebSocket.
- Extensibility: Socket.IO supports horizontal expansion, which can extend the application to multiple servers and realize the broadcast and delivery of events. This allows applications to handle large-scale concurrent connections and achieve high availability and performance
nodejs installation
npm install socket.io
The browser uses esm
<script type="module">
import { io } from "https://cdn.socket.io/4.7.4/socket.io.esm.min.js"
const socket = io("ws://localhost:3000") //ws的地址
</script>
Chat Room


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
html,
body,
.room {
height: 100%;
width: 100%;
}
.room {
display: flex;
}
.left {
width: 300px;
border-right: 0.5px solid #f5f5f5;
background: #333;
}
.right {
background: #1c1c1c;
flex: 1;
display: flex;
flex-direction: column;
}
.header {
background: #8d0eb0;
color: white;
padding: 10px;
box-sizing: border-box;
font-size: 20px;
}
.main {
flex: 1;
padding: 10px;
box-sizing: border-box;
font-size: 20px;
overflow: auto;
}
.main-chat {
color: green;
}
.footer {
min-height: 200px;
border-top: 1px solid green;
}
.footer .ipt {
width: 100%;
height: 100%;
color: green;
outline: none;
font-size: 20px;
padding: 10px;
box-sizing: border-box;
}
.groupList {
height: 100%;
overflow: auto;
}
.groupList-items {
height: 50px;
width: 100%;
background: #131313;
display: flex;
align-items: center;
justify-content: center;
color: white;
}
</style>
</head>
<div class="room">
<div class="left">
<div class="groupList"></div>
</div>
<div class="right">
<header class="header">聊天室</header>
<main class="main"></main>
<footer class="footer">
<div class="ipt" contenteditable></div>
</footer>
</div>
</div>
<body>
<script type="module">
const sendMessage = (message) => {
const div = document.createElement("div")
div.className = "main-chat"
div.innerText = `${message.user}:${message.text}`
main.appendChild(div)
}
const groupEl = document.querySelector(".groupList")
const main = document.querySelector(".main")
import { io } from "https://cdn.socket.io/4.7.4/socket.io.esm.min.js"
const name = prompt("请输入你的名字")
const room = prompt("请输入房间号")
const socket = io("ws://localhost:3000")
//键盘按下发送消息
document.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault()
const ipt = document.querySelector(".ipt")
socket.emit("message", {
text: ipt.innerText,
room: room,
user: name,
})
sendMessage({
text: ipt.innerText,
user: name,
})
ipt.innerText = ""
}
})
//连接成功socket
socket.on("connect", () => {
socket.emit("join", { name, room }) //加入一个房间
socket.on("message", (message) => {
sendMessage(message)
})
socket.on("groupList", (groupList) => {
console.log(groupList)
groupEl.innerHTML = ""
Object.keys(groupList).forEach((key) => {
const item = document.createElement("div")
item.className = "groupList-items"
item.innerText = `房间名称:${key} 房间人数:${groupList[key].length}`
groupEl.appendChild(item)
})
})
})
</script>
</body>
</html>
nodejs
import http from "http"
import { Server } from "socket.io"
import express from "express"
const app = express()
app.use("*", (req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*")
res.setHeader("Access-Control-Allow-Headers", "*")
res.setHeader("Access-Control-Allow-Methods", "*")
next()
})
const server = http.createServer(app)
const io = new Server(server, {
cors: true, //允许跨域
})
const groupList = {}
/**
* [{1008:[{name,room,id}]}]
*/
io.on("connection", (socket) => {
//加入房间
socket.on("join", ({ name, room }) => {
socket.join(room)
if (groupList[room]) {
groupList[room].push({ name, room, id: socket.id })
} else {
groupList[room] = [{ name, room, id: socket.id }]
}
socket.emit("message", { user: "管理员", text: `${name}进入了房间` })
socket.emit("groupList", groupList)
socket.broadcast.emit("groupList", groupList)
})
//发送消息
socket.on("message", ({ text, room, user }) => {
socket.broadcast.to(room).emit("message", {
text,
user,
})
})
//断开链接内置事件
socket.on("disconnect", () => {
Object.keys(groupList).forEach((key) => {
let leval = groupList[key].find((item) => item.id === socket.id)
if (leval) {
socket.broadcast
.to(leval.room)
.emit("message", { user: "管理员", text: `${leval.name}离开了房间` })
}
groupList[key] = groupList[key].filter((item) => item.id !== socket.id)
})
socket.broadcast.emit("groupList", groupList)
})
})
server.listen(3000, () => {
console.log("listening on *:3000")
})
Nodejs Chapter 56 (Crawler)
What is a crawler?
A crawler, also known as a web crawler or web spider, refers to an automated program or script used to browse and extract information on the Internet. The crawler simulates the behavior of human users on the web page, sends requests through the HTTP protocol, obtains the web page content, and then parses and extracts the data of interest.
When using the crawler, you need to comply with the terms of use of
Laws and regulationsand the website
- Website Terms of Use: Each website has its own terms of use and privacy policy, which set forth restrictions on access to and use of the website’s content and data. Be sure to carefully read and comply with the website's terms of use before using the crawler.
- Intellectual property rights: Crawlers may involve copying, extracting or distributing content on the website. In doing so, you should respect intellectual property laws, including copyright and trademark laws. Make sure you have the legal rights to use, copy or distribute the scraped content.
- Network damage and abuse: When using crawlers, you should avoid causing unnecessary load, interference, or damage to the target website. Crawlers may not be used in malicious ways, such as conducting DDoS attacks, cracking security measures, or illegally collecting personal information.
- Data privacy and personal information protection: When crawling data on websites, special attention needs to be paid to the compliance of handling personally identifiable information and private data. Comply with applicable data protection laws and ensure that user data is processed and stored lawfully.
- Fraud and Abuse: You may not use crawlers to engage in fraud, counterfeiting, spamming, or other illegal activities. Respect the interests of other users and websites and abide by the principles of fair competition
Install dependencies
nodejs
npm install puppeteer #爬虫 | 自动化UI测试
Puppeteer is a Node.js library developed and maintained by Google that provides a high-level API for controlling and automating web page operations through Headless Chrome or Chromium. It can simulate user interaction in the browser, such as clicking, filling out forms, taking screenshots, generating PDF, etc. It can also obtain the content of the web page and execute JavaScript code.
Here are some of Puppeteer’s key features:
- Automated browser operations: Puppeteer can run Chrome or Chromium in headless mode to realize automated operations on web pages, including loading pages, clicking, filling out forms, submitting, etc. It also supports simulating user behaviors such as mouse movement, keyboard input, etc.
- Screenshot and generate PDF: Puppeteer can take screenshots of pages, save them as image files, and also generate PDF files. This is useful for taking snapshots of web pages, generating reports, conducting page testing, etc.
- Crawler and data scraping: Puppeteer can help you write web crawler and data scraping scripts. You can simulate user behavior to navigate web pages, extract content, execute JavaScript code, and save the data locally or perform further processing.
- Web page performance analysis: Puppeteer provides some APIs for analyzing web page performance, such as measuring page loading time, network requests and resource usage, etc. This is useful for performance optimization and monitoring.
- Headless mode and debugging mode: Puppeteer can run in headless mode, that is, running Chrome or Chromium in the background without displaying the browser interface. Additionally, it supports debug mode, allowing you to inspect and debug pages during development.
python
pip install wordcloud #生成词云图
pip install jieba #中文分词
- WordCloud:
WordCloud is a Python library for generating word clouds. It can generate a beautiful word cloud image based on word frequency based on given text data, where the size of a word represents its importance or frequency in the text. The WordCloud library provides a wealth of configuration options to control the appearance, color, font and other properties of the word cloud. You can customize the style and layout of the word cloud according to your needs. WordCloud also provides some convenient methods for extracting keywords from text, filtering stop words, and more. You can use pip to install the WordCloud library and refer to the official documentation for use. 2. jieba:
Jieba is an open source Chinese word segmentation library used to segment Chinese text into individual words. Chinese word segmentation is an important task in NLP (natural language processing). The jieba library provides an effective and flexible word segmentation algorithm that can accurately identify word boundaries in Chinese text. jieba supports three word segmentation modes: precise mode, full mode and search engine mode. You can choose the appropriate word segmentation mode according to your needs
Code example
puppeteer will automatically open the browser and click on the parameters you passed in, such as the front-end, it will automatically click on the front-end menu, then get the recommended data, hand it to python, perform Chinese semiword, and output Word clouds after dividing the words.
index.js
import puppeteer from "puppeteer"
import { spawn } from "child_process"
const btnText = process.argv[2]
const browser = await puppeteer.launch({
headless: false, //取消无头模式
})
const page = await browser.newPage() //打开一个页面
page.setViewport({ width: 1920, height: 1080 }) //设置页面宽高
await page.goto("https://juejin.cn/") //跳转到掘金
await page.waitForSelector(".side-navigator-wrap") //等待这个元素出现
const elements = await page.$(".side-navigator-wrap .nav-item-wrap span") //获取menu下面的span
const articleList = []
const collectFunc = async () => {
//获取列表的信息
await page.waitForSelector(".entry-list")
const elements = await page.$(".entry-list .title-row a")
for await (let el of elements) {
const text = await el.getProperty("innerText")
const name = await text.jsonValue()
articleList.push(name)
}
console.log(articleList)
//调用python脚本进行中文分词 输出词云图
const pythonProcess = spawn("python", ["index.py", articleList.join(",")])
pythonProcess.stdout.on("data", (data) => {
console.log(data.toString())
})
pythonProcess.stderr.on("data", (data) => {
console.log(data.toString())
})
pythonProcess.on("close", (code) => {
console.log(`child process exited with code ${code}`)
})
}
for await (let el of elements) {
const text = await el.getProperty("innerText") //获取span的属性
const name = await text.jsonValue() //获取内容
if (name.trim() === (btnText || "前端")) {
await el.click() //自动点击对应的菜单
collectFunc() //调用函数
}
}
index.py
import jieba #引入结巴库
from wordcloud import WordCloud #引入词云图
import matplotlib.pyplot as plt
import sys
text = sys.argv[1]
words = jieba.cut(text) #中文分词
#添加字体文件 随便找一个字体文件就行 不然不支持中文
font = './font.ttf'
info = WordCloud(font_path=font,width=1000,height=800,background_color='white').generate(''.join(words))
#输出词云图
plt.imshow(info,interpolation='bilinear')
plt.axis('off')
plt.show()
Effect display (Yell clouds)

Nodejs Chapter 57 (addon)

Nodejs has extremely strong capabilities in IO, but it is insufficient for CPU-intensive tasks. In order to fill this shortcoming, Nodejs supports c/c++ to write native nodejs plug-ins to supplement this ability.
Nodejs c++ extension
Code written in C++ can be compiled into a dynamic link library (dll), which can be introduced and used by nodejs require. The suffix is .node
The principle of .node file is (window dll) (Mac dylib) (Linux so)
c++ extension writing syntax
- NAN (Native Abstractions for Nodejs) Write once, compile everywhere
- Because both Nodejs and V8 are updated very quickly, the method names of each version are also different, which causes a big problem for our development. For example
- Version 0.50
Echo(const Prototype&proto) - Version 3.00
Echo(Object<Prototype>& proto)
NAN is a bunch of macro judgments to judge various versions of API to achieve compatibility, so it will be compiled everywhere 2. N-API (node-api) does not need to be recompiled
- C-based API
- c++ package node-addon-api
N-API is a more modern option that provides a stable, cross-version API, allowing your plugin to run on different versions of Node.js without modifying the code. This greatly simplifies the process of writing and maintaining plugins.
For C++, you can use node-addon-api, which is a wrapper around N-API that provides an easier-to-use C++ API. This will make your code easier to read and maintain.
Usage scenarios
- Use Nodejs libraries written in C++ such as
node-sassnode-jieba, etc. - CPU-intensive applications
- Code protection
Dependencies that need to be installed
npm install --global --production windows-build-tools #管理员运行
#如果安装过python 以及c++开发软件就不需要装这个了
npm install node-gyp -g #全局安装
npm install node-addon-api -D #装到项目里
Small case to obtain the width and height of the device
index.cpp
#define NAPI_VERSION 3 //指定addon版本
#define NAPI_CPP_EXCEPTIONS //启用 Node.js N-API 中的 C++ 异常支持
#include <napi.h> //addon API
#include <windows.h> //windwos API
Napi::Value GetScreenSize(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env(); //指定环境
int cx = GetSystemMetrics(SM_CXSCREEN); //获取设备宽
int cy = GetSystemMetrics(SM_CYSCREEN); //获取设备高
Napi::Object result = Napi::Object::New(env); //创建一个对象
result.Set("width", cx);
result.Set("height", cy);
return result; //返回对象
}
Napi::Object Init(Napi::Env env, Napi::Object exports) {
//抛出一个函数 getScreenSize
exports.Set("getScreenSize", Napi::Function::New(env, GetScreenSize));
return exports;
}
//addon固定语法 必须抛出这个方法
NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init)
binding.gyp
{
"targets": [
{
"target_name": "cpu", //名称
"sources": ["cpu.cpp"], //指定文件
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")" //引入addon
]
}
]
}
index.js
const addon = require("./build/Release/cpu.node")
console.log(addon.getScreenSize())
node-gyp configure #生成配置文件
node-gyp build #打包addon

Nodejs Chapter 58 (Large File Upload)

In modern websites, more and more personalized pictures and videos are displayed, so our websites generally support file uploads.
File upload plan
Upload Big Files: Split a large file into smaller pieces (often called slices or chunks) and then upload those slices one by one. This method can improve the stability of uploading, because if a certain part fails to upload, only that part needs to be re-uploaded without the need to re-upload the entire file. At the same time, multi-part upload can also use multiple network connections to upload multiple parts in parallel to increase upload speed.Breakpoint: During the upload process, if the network is interrupted or the upload is aborted, the breakpoint resume technology can record the successfully uploaded fragment information so that when the upload is resumed, the unfinished part can be continued to be uploaded without the need to re-upload the entire file. This technique can greatly reduce the impact of upload failures and save time and bandwidth.
Front-end implementation
<input id="file" type="file" />
<!--用来上传文件-->
Listen to the change event to obtain the file file and implement a method chunkFun for slicing
const file = document.getElementById("file")
file.addEventListener("change", (event) => {
const file = event.target.files[0] //获取文件信息
const chunks = chunkFun(file)
uploadFile(chunks)
})
File slice file accepts file objects. Note that the bottom layer of file is inherited from blob, so it can call the method of blob. Slice performs slicing. Size is the size of each slice. I used 4MB here. It can actually be determined according to the project situation.
const chunkFun = (file, size = 1024 * 1024 * 4) => {
const chunks = []
for (let i = 0; i < file.size; i += size) {
chunks.push(file.slice(i, i + size))
}
return chunks
}
Call the interface to upload in a loop and store some information, Index of the current fraction. Note that the file must be written at the last one, because multer on the nodejs side will be read in order, otherwise the parameters cannot be read. Finally, send requests concurrently through promise.all, wait for all requests to be sent, and notify the backend to merge the slices.
const uploadFile = (chunks) => {
const List = []
for (let i = 0; i < chunks.length; i++) {
const formData = new FormData()
formData.append("index", i)
formData.append("total", chunks.length)
formData.append("fileName", "xiezhen")
formData.append("file", chunks[i])
List.push(
fetch("http://127.0.0.1:3000/up", {
method: "POST",
body: formData,
})
)
}
Promise.all(List).then((res) => {
fetch("http://127.0.0.1:3000/merge", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
fileName: "xiaoManXieZhen",
}),
}).then((res) => {
console.log(res)
})
})
}
Nodejs side implementation
Install dependencies
- express helps us start the service and provide an interface
- multer reads files and stores
- cors solves cross-domain issues
Import module
import express from "express"
import multer from "multer"
import cors from "cors"
import fs from "node:fs"
import path from "node:path"
Provide two interfaces
- up is used to store slices
- merge merge slices
Initialize multer.diskStorage
- destination storage directory
- filename is the stored file name (I stored it through index-file name, you can also change it)
merge logic
Read all files under the upload directory, that is, all slices
0-xiezhen
1-xiezhen
2-xiezhen
3-xiezhen
What is returned after reading is an array, but it will be out of order when reading, so sort it from small to large and use sort. After sorting, read the contents of each slice, merge it into a file through fs.appendFileSync, and finally delete the merged slices to complete. respect
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "uploads/")
},
filename: (req, file, cb) => {
cb(null, `${req.body.index}-${req.body.fileName}`)
},
})
const upload = multer({ storage })
const app = express()
app.use(cors())
app.use(express.json())
app.post("/up", upload.single("file"), (req, res) => {
res.send("ok")
})
app.post("/merge", async (req, res) => {
const uploadPath = "./uploads"
let files = fs.readdirSync(path.join(process.cwd(), uploadPath))
files = files.sort((a, b) => a.split("-")[0] - b.split("-")[0])
const writePath = path.join(
process.cwd(),
`video`,
`${req.body.fileName}.mp4`
)
files.forEach((item) => {
fs.appendFileSync(
writePath,
fs.readFileSync(path.join(process.cwd(), uploadPath, item))
)
fs.unlinkSync(path.join(process.cwd(), uploadPath, item))
})
res.send("ok")
})
app.listen(3000, () => {
console.log("Server is running on port 3000")
})

Nodejs Chapter 59 (File Stream Download)
File streaming download is a method of downloading files by sending the file content to the client in the form of a stream. It is suitable for processing large files or when the file content needs to be generated in real time.
Install dependencies
npm install express #启动服务 提供接口
npm install cors #解决跨域
nodejs full version code
Core knowledge response header
Content-Typespecifies the MIME type of the downloaded file
application/octet-stream(binary stream data)application/pdf: Adobe PDF file.application/json: JSON data fileimage/jpeg: JPEG image file
Content-Dispositionspecifies how the content returned by the server is processed in the browser. It can be used to control file downloads, inline display, or other processing
attachment: Instructs the browser to download the response content as an attachment. Typically used with thefilenameparameter to specify the name of the downloaded fileinline: Instructs the browser to open the response content directly in the browser window, or display it inline in the browser if the content is a recognized file type (such as an image or PDF)
import express from "express"
import fs from "fs"
import path from "path"
import cors from "cors"
const app = express()
app.use(cors())
app.use(express.json())
app.use(express.static("./static"))
app.post("/download", function (req, res) {
const fileName = req.body.fileName
const filePath = path.join(process.cwd(), "./static", fileName)
const content = fs.readFileSync(filePath)
res.setHeader("Content-Type", "application/octet-stream")
res.setHeader("Content-Disposition", "attachment;filename=" + fileName)
res.send(content)
})
app.listen(3000, () => {
console.log("http://localhost:3000")
})

Front-end logic
The core logic of the front-end is to accept the return value in the form of stream arrayBuffer, convert it into a blob, generate a download link, and simulate a tag click to download.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button id="btn">download</button>
<script>
const btn = document.getElementById("btn")
btn.onclick = () => {
fetch("http://localhost:3000/download", {
method: "post",
body: JSON.stringify({
fileName: "1.png",
}),
headers: {
"Content-Type": "application/json",
},
})
.then((res) => res.arrayBuffer())
.then((res) => {
const blob = new Blob([res], { type: "image/png" })
const url = URL.createObjectURL(blob)
const a = document.createElement("a")
a.href = url
a.download = "1.png"
a.click()
})
}
</script>
</body>
</html>

Nodejs Chapter 60 (http cache)
HTTP Cache
HTTP caches are mainly divided into two categories: Strong Cache and Consultation Cache. Both caches are controlled via HTTP response headers and are intended to improve website performance.
Introduction to strong caching
After strong caching, there is no need to send a request to the server, but reading from the browser cache is divided into (Memory Cache) | (Hard Disk Cache)

- memory cache The memory cache is stored in the browser memory. Generally, when refreshing the web page, you will find many memory caches.
- disk cache (hard disk cache) The hard disk cache is stored in the computer hard disk and has a large space, but the reading efficiency is slower than the memory cache.
Strong cache case (Expires)
Expires: This field specifies the expiration time of the response, that is, the date and time when the resource is no longer considered valid. It is an HTTP 1.0 header field but is still used by some clients and servers.
The judgment mechanism of Expires is: when the client requests a resource, it will obtain the local timestamp, and then Compare local timestamps with Expires settings. If the comparison is successful, the cache will be strengthened. If the comparison fails, a request will be made to the server.
node side
import express from "express"
import cors from "cors"
const app = express()
app.use(cors())
app.get("/", (req, res) => {
res.setHeader("Expires", new Date("2024-3-30 23:17:00").toUTCString()) //设置过期时间
res.json({
name: "cache",
version: "1.0.0",
})
})
app.listen(3000, () => {
console.log("Example app listening on port 3000!")
})
web request
<body>
<button id="btn">send</button>
<script>
const btn = document.getElementById("btn")
btn.addEventListener("click", () => {
fetch("http://localhost:3000")
})
</script>
</body>
Use the cached value before expiration, and read it from the server after expiration

Strong cache case (Cache-Control)
The values for Cache-Control are as follows:
max-age: Browser resource cache duration (seconds).no-cache: Do not use strong caching, but use negotiated caching.no-store: Disable any cache policy.public: Resources can be cached by browsers or proxy servers (CDN).private: The resource can only be cached by the client.
If max-age and Expires appear at the same time, max-age has higher priority
node side
import express from "express"
import cors from "cors"
const app = express()
app.use(cors())
app.get("/", (req, res) => {
res.setHeader("Cache-Control", "public, max-age=20") //20秒
res.json({
name: "cache",
version: "1.0.0",
})
})
app.listen(3000, () => {
console.log("Example app listening on port 3000!")
})

Introduction to negotiation cache
When it comes to caching mechanisms, strong caching takes precedence over negotiated caching. When strong caching of resources is in effect, the client can obtain the resource directly from the local cache without communicating with the server. The judgment of strong caching is done by caching header fields, for example, setting the appropriate Cache-Control and Expires fields.
If the strong cache misses (for example, max-age expires), or Cache-Control: no-cache is set in the server response, the client will initiate a request to negotiate the cache. In negotiating cache, the client sends a request header field with cache data identification to verify the validity of the resource to the server.
The server will determine whether the resource has changed based on the negotiation cache fields sent by the client (such as If-Modified-Since and If-None-Match). If the resource has not been modified, the server will return status code 304 (Not Modified) to notify the client that the cached version can be used. If the resource has changed, the server will return the latest resource with status code 200.
Negotiation cache (Last-Modified)
Last-Modified and If-Modified-Since: The server informs the client of the last modification time of the resource through the Last-Modified response header. The client carries the time in subsequent requests through the If-Modified-Since request header, and the server determines whether the resource has been updated. If there is no update, a 304 status code is returned.
nodejs side
import express from "express"
import cors from "cors"
import fs from "node:fs"
const getModifyTime = () => {
return fs.statSync("./index.js").mtime.toISOString() //获取文件最后修改时间
}
const app = express()
app.use(cors())
app.get("/api", (req, res) => {
res.setHeader("Cache-Control", "no-cache, max-age=2592000") //表示走协商缓存
const ifModifiedSince = req.headers["if-modified-since"] //获取浏览器上次修改时间
res.setHeader("Last-Modified", getModifyTime())
if (ifModifiedSince && ifModifiedSince === getModifyTime()) {
console.log("304")
res.statusCode = 304
res.end()
return
} else {
console.log("200")
res.end("value")
}
})
app.listen(3000, () => {
console.log("Example app listening on port 3000!")
})

Negotiation cache (ETag)
ETag and If-None-Match: The server generates a unique identifier for the resource through the ETag response header. The client carries the identifier through the If-None-Match request header in subsequent requests, and the server determines whether the resource has been updated based on the identifier. If there is no update, a 304 status code is returned.
ETag has a higher priority than Last-Modified
import express from "express"
import cors from "cors"
import fs from "node:fs"
import crypto from "node:crypto"
const getFileHash = () => {
return crypto
.createHash("sha256")
.update(fs.readFileSync("index.js"))
.digest("hex")
}
const app = express()
app.use(cors())
app.get("/api", (req, res) => {
res.setHeader("Cache-Control", "no-cache, max-age=2592000") //表示走协商缓存
const etag = getFileHash()
const ifNoneMatch = req.headers["if-none-match"]
if (ifNoneMatch === etag) {
res.sendStatus(304)
return
}
res.setHeader("ETag", etag)
res.send("Etag")
})
app.listen(3000, () => {
console.log("Example app listening on port 3000!")
})

Nodejs Chapter 61 (http2)
http2
HTTP/2 (HTTP2) is the next major version of the Hypertext Transfer Protocol (HTTP) and is a major improvement over the HTTP/1.1 protocol. The goal of HTTP/2 is to improve performance, efficiency, and security to provide faster and more efficient network communications
How to tell whether it is http/1.1 or http2

- Multiplexing: HTTP/2 supports sending multiple requests and responses simultaneously on a single TCP connection. This means multiple connections can be avoided, network latency reduced, and efficiency improved.

- Binary Framing:
Binary Frameis added between the application layer (HTTP2) and the transport layer (TCP or UDP) to split the request and response into multiple frames. The design of this binary format makes the protocol more efficient and easy to parse and process.
Frame: The smallest communication unit, carrying specific types of data, such as HTTP headers and payloads
HTTP/2 frame type:
- Data Frame: used to transmit the actual data of requests and responses.
- Headers Frame: Contains header information of the request or response.
- Priority Frame: used to specify the priority of the request.
- Settings Frame: used to transmit communication parameter settings.
- Push Promise Frame: used for the server to actively push resources.
- PING Frame: used to detect the activity of the connection.
- Reset frame (RST_STREAM Frame): used to reset the data stream or notify errors.

- Header Compression: HTTP/2 uses a header table and a dynamic compression algorithm to reduce the size of the header. This reduces the overhead of each request and response and improves transfer efficiency.
The first request sends all header fields, and the second request only needs to send differential data, which can reduce redundant data and reduce overhead.

nodejs implements http2
As of 2024-4-2, currently no browser supports http requests to access http2, so https must be used
You can use openssl to generate tls certificate
- Generate private key
openssl genrsa -out server.key 1024
- Generate a certificate request file (you can delete or keep it after use)
openssl req -new -key server.key -out server.csr
- Generate certificate
openssl x509 -req -in server.csr -out server.crt -signkey server.key -days 3650
import http2 from "node:http2"
import fs from "node:fs"
const server = http2.createSecureServer({
key: fs.readFileSync("server.key"),
cert: fs.readFileSync("server.crt"),
})
server.on("stream", (stream, headers) => {
stream.respond({
"content-type": "text/html; charset=utf-8",
":status": 200,
})
stream.on("error", (err) => {
console.log(err)
})
stream.end(`
<h1>http2</h1>
`)
})
server.listen(80, () => {
console.log("server is running on port 80")
})
Nodejs Chapter 62 (short link)
Introduction to short links
Shortlinking is a method of shortening long URLs, converting the original long URL into a shorter form. It usually consists of a series of letters, numbers and special characters. Compared with the original long URL, a short link is more concise, easier to remember and share.
One of the main uses of short links is for link sharing on social media platforms. Since these platforms have restrictions on the number of characters, long URLs may take up a lot of space. Therefore, using short links can save characters and is more convenient to use in scenarios where the number of characters is limited, such as Twitter and text messages.
In addition, short links can also be used to track and count link clicks. By embedding the tracking code in the short link, the website administrator can obtain detailed statistics on the clicked link, including the number of visits, source, geographical location and other information. This is useful for marketing campaigns, advertising or analyzing link performance.
For example SMS


The implementation principle is roughly to generate a Only short code and use redirection to set the original long connection address.
Code implementation
required dependencies
- epxress starts the service providing interface
- mysql2 knex relies on connecting to the database
- knex orm framework operates mysql
- shortid generates a unique short code
Database design
CREATE TABLE `short` (
`id` int NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
`short_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '短码',
`url` varchar(255) NOT NULL COMMENT '网址',
PRIMARY KEY (`id`)
)
nodejs side
import knex from "knex"
import express from "express"
import shortid from "shortid"
const app = express()
app.use(express.json())
const db = knex({
client: "mysql2",
connection: {
host: "localhost",
user: "root",
password: "123456",
database: "short_link",
},
})
//生成短码 存入数据库
app.post("/create_url", async (req, res) => {
const { url } = req.body
const short_id = shortid.generate()
const result = await db("short").insert({ short_id, url })
res.send(`http://localhost:3000/${short_id}`)
})
//重定向
app.get("/:shortUrl", async (req, res) => {
const short_id = req.params.shortUrl
const result = await db("short").select("url").where("short_id", short_id)
if (result && result[0]) {
res.redirect(result[0].url)
} else {
res.send("Url not found")
}
})
app.listen(3000, () => {
console.log("Server is running on port 3000")
})
Test
Link after generation

Visit link redirect to destination URL

Nodejs Chapter 63 (Serial Port Technology)
Serial port introduction
Serial port technology is a communication technology used for data transmission between computers and external devices. It sends and receives data bit by bit through serial transmission.
Common serial devices include scanners, printers, sensors, controllers, collectors, electronic scales, etc.
SerialPort
SerialPort is a popular Node.js module for communicating with external devices over a serial port in your computer. It provides a powerful set of APIs for opening, reading, writing, and closing serial connections, and supports a variety of operating systems and serial devices. SerialPort official website
The main functions of the SerialPort module include:
- Open the serial port connection: Using the SerialPort module, you can easily open the serial port connection and specify the serial port name, baud rate, data bits, stop bits, check bits and other parameters.
- Reading and writing data: Through the SerialPort module, the data stream can be read from the serial port and written to the serial port. You can use event handlers or callback functions to handle read and write operations.
- Configure serial port parameters: SerialPort supports configuring various parameters of the serial port, such as baud rate, data bits, stop bits, parity bits, etc. Can be customized according to needs.
- Control flow control: SerialPort allows the application of hardware flow control or software flow control in serial communication to control the data transmission rate and process.
- Event processing: The SerialPort module can monitor various events of the serial port connection, such as opening, closing, errors, etc., in order to process and respond in a timely manner.
Case communication with microcontroller
Here I use 51 microcontroller

Software that needs to be installed
Keil uVision5Write microcontroller codestcai-ispburning microcontroller program
Microcontroller serial communication programming
#include <REGX51.H>
#include <STDIO.h>
sbit LED = P1^0; //
void UART_Init() {
SCON = 0x50; //工作方式
PCON = 0x00; //32分频
TMOD = 0x20; //计数器工作方式
TH1 = 0xFD;
TL1 = 0xFD;
ES = 1; //接受中断
EA = 1; //打开总中断
TR1 = 1; //打开计数器
}
void main ()
{
UART_Init(); //调用初始化函数
while(1);
}
void uart()interrupt 4
{
unsigned char date;
date = SBUF; //接受数据
if(date == '1'){
LED = 0; //开灯
}else if(date == '0'){
LED = 1; //关灯
}
RI = 0;
}
Burn to microcontroller

Nodejs side writing
Install serialport
npm install serialport
Code writing
import { SerialPort } from "serialport"
const serialPort = new SerialPort({
path: "COM4", //单片机串口
baudRate: 9600, //波特率
})
serialPort.on("data", () => {
console.log("data") //监听单片机的消息
})
let flag = 1
setInterval(() => {
serialPort.write(flag + "") //跟单片机进行通讯 传值
flag = Number(!flag)
console.log(flag == 0 ? "开" : "关") //进行开关的切换
}, 2000)

Nodejs Chapter 64 (SSO single sign-on)
Single sign-on
Single Sign-On (SSO) is an identity authentication and access control mechanism that allows users to log in to multiple applications or systems using a set of credentials (such as username and password) without having to provide separate credentials for each application.
The main advantages of SSO include:
- User-friendliness: Users only need to log in once to access multiple applications, providing a better user experience and convenience.
- Improve security: With centralized authentication, password leaks and password management issues can be reduced. In addition, SSO can be combined with other authentication mechanisms, such as multi-factor authentication, to provide stronger security.
- Simplified management: SSO can reduce the workload of administrators as they do not need to manage user credentials and permissions individually for each application.
Examples
Xiaoman Technology and Xiaoman Education are both companies under Xiaoman, so I need to do a set of login registration and personnel management for each system. That is too laborious, so I use SSO single sign-on, Just login at any one application, and other applications are one of the effects of de-logining, if expired, re-entry.
But each application is different, and you use one set for login. At this time, you can imitate the WeChat applet to generate an AppId as the application ID, and you can also create a secret. Because the permissions of each application can be different, the final generated tokens are also different. You also need a URL to redirect to the address of the application after logging in. The formal approach requires a background management system to control these, register applications, and delete applications. This saves time.

Code writing
- Installed dependencies
- express starts the service writing interface
- express-session operation cookie
- jsonwebtoken generates token
- cors cross domain
- Directory structure
- vue A project
Use vite to create a new npm init vite - react B project
Use vite to create a new npm init vite - server/index.js nodejs side
- sso.html login page
server/index.js
const appToMapUrl = {
//A应用id
Rs6s2aHi: {
url: "http://localhost:5173", //对应的应用地址
secretKey: "%Y&*VGHJKLsjkas", //对应的secretKey
token: "", //token
},
//B应用id
"9LQ8Y3mB": {
url: "http://localhost:5174", //对应的应用地址
secretKey: "%Y&*FRTYGUHJIOKL", //对应的secretKey
token: "", //token
},
}
Full version code
server/index.js
import express from "express"
import session from "express-session"
import fs from "node:fs"
import cors from "cors"
import jwt from "jsonwebtoken"
const appToMapUrl = {
Rs6s2aHi: {
url: "http://localhost:5173",
name: "vue",
secretKey: "%Y&*VGHJKLsjkas",
token: "",
},
"9LQ8Y3mB": {
url: "http://localhost:5174",
secretKey: "%Y&*FRTYGUHJIOKL",
name: "react",
token: "",
},
}
const app = express()
app.use(cors())
app.use(express.json())
app.use(
session({
secret: "$%^&*()_+DFGHJKL",
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 7, //过期时间
},
})
)
const genToken = (appId) => {
return jwt.sign({ appId }, appToMapUrl[appId].secretKey)
}
app.get("/login", (req, res) => {
//注意看逻辑 如果登陆过 就走if 没有登录过就走下面的
if (req.session.username) {
//登录过
const appId = req.query.appId
const url = appToMapUrl[appId].url
let token
//登录过如果存过token就直接取 没有存过就生成一个 因为可能有多个引用A登录过读取Token B没有登录过生成Token 存入映射表
if (appToMapUrl[appId].token) {
token = appToMapUrl[appId].token
} else {
token = genToken(appId)
appToMapUrl[appId].token = token
}
res.redirect(url + "?token=" + token)
return
}
//没有登录 返回一个登录页面html
const html = fs.readFileSync(`../sso.html`, "utf-8")
//返回登录页面
res.send(html)
})
//提供protectd get接口 重定向到目标地址
app.get("/protectd", (req, res) => {
const { appId, username, password } = req.query //获取应用标识
const url = appToMapUrl[appId].url //读取要跳转的地址
const token = genToken(appId) //生成token
req.session.username = username //存储用户名称 表示这个账号已经登录过了 下次无需登录
appToMapUrl[appId].token = token //根据应用存入对应的token
res.redirect(url + "?token=" + token) //定向到目标页面
})
//启动3000端口
app.listen(3000, () => {
console.log("http://localhost:3000")
})
sso.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<!--这里会调用protectd接口 并且会传入 账号 密码 和 appId appId会从地址栏读取-->
<form action="/protectd" method="get">
<label for="username">
账号:<input name="username" id="username" type="text" />
</label>
<label for="password"
>密码:<input name="password" id="password" type="password"
/></label>
<label for="appId"
><input name="appId" value="" id="appId" type="hidden"
/></label>
<button type="submit" id="button">登录</button>
</form>
<script>
//读取AppId
const appId = location.search.split("=")[1]
document.getElementById("appId").value = appId
</script>
</body>
</html>
A application is displayed here using Vue App.vue
<template>
<h1>vue3</h1>
</template>
<script setup lang="ts">
//如果有token代表登录过了 如果没有跳转到 登录页面也就是SSO 那个页面,并且地址栏携带AppID
const token = location.search.split("=")[1]
if (!token) {
fetch("http://localhost:3000/login?appId=Rs6s2aHi").then((res) => {
location.href = res.url
})
}
</script>
<style></style>
B application uses React to demonstrate App.tsx
import { useState } from "react"
function App() {
const [count, setCount] = useState(0)
//逻辑其实一样的只是区分了不用应用的AppId
const token = location.search.split("=")[1]
if (!token) {
fetch("http://localhost:3000/login?appId=9LQ8Y3mB").then((res) => {
location.href = res.url
})
}
return (
<>
<h1>react</h1>
</>
)
}
export default App

Nodejs Chapter 65 (SDL Single Device Login)
Single device login
SDL (Single Device Login) is a single device login mechanism that allows users to log in on only one device at the same time. When the user logs in on other devices, the previously logged in device will be pushed offline.
Application scenarios
- Video and audio, prevent one account from being shared, and prevent some account dealers
- Social Media Platforms: Social media platforms typically have multiple security measures in place to protect user accounts, one of which is single-device login. This prevents unauthorized access to your account and protects your personal information and privacy.
- For online shopping and electronic payment platforms, users’ payment information and order details are sensitive. Single-device login adds an extra layer of security when users perform payment operations, ensuring that only authorized devices can perform payment operations.
- For email and messaging applications, users’ personal and confidential information is stored there. Through the single-device login mechanism, it can ensure that the user's email or communication application can only be logged in on one device to prevent the account from being maliciously used by others.
Implementation ideas
Design data structure
{
id: {
socket: ws实例
fingerprint: 浏览器指纹
}
}
- When logging in for the first time, record the user ID, socket information, and browser fingerprint.
- When another device logs in and finds that it has been connected before, it uses the old socket to send an offline notification, closes the old socket, and updates the socket to replace it with the ws connection of the current new device.
Browser fingerprint
There are many kinds of fingerprint technology, here we use Canvas fingerprint technology
The website passes these color values to an algorithm, which performs complex calculations on the data to generate a unique identifier. Due to differences in the operating systems, browsers, GPUs, and drivers used by users, differences will occur when drawing graphics. These subtle differences will lead to different generated identifiers (hash values). Therefore, each user can generate a unique Canvas fingerprint
Implementation code
nodejs side
import express from "express"
import { WebSocketServer } from "ws"
import cors from "cors"
const app = express()
app.use(cors())
app.use(express.json())
//存放数据结构
const connection = {}
const server = app.listen(3000)
const wss = new WebSocketServer({ server })
wss.on("connection", (ws) => {
ws.on("message", (message) => {
const data = JSON.parse(message)
if (data.action === "login") {
if (connection[data.id] && connection[data.id].fingerprint) {
console.log("账号在别处登录")
//提示旧设备
connection[data.id].socket.send(
JSON.stringify({
action: "logout",
message: `你于${new Date().toLocaleString()}账号在别处登录`,
})
)
connection[data.id].socket.close() //断开旧设备连接
connection[data.id].socket = ws //更新ws
} else {
console.log("首次登录")
connection[data.id] = {
socket: ws, //记录ws
fingerprint: data.fingerprint, //记录指纹
}
}
}
})
})
Browser side
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>SDL</h1>
<script src="./md5.js"></script>
<script>
//浏览器指纹
const createBrowserFingerprint = () => {
const canvas = document.createElement("canvas")
const ctx = canvas.getContext("2d")
ctx.fillStyle = "red"
ctx.fillRect(0, 0, 1, 1)
return md5(canvas.toDataURL())
}
//谷歌abf12f62e03d160f7f24144ef1778396
//火狐80bea69bfc7cad5832d12e41714cf677
//Edge abf12f62e03d160f7f24144ef1778396
const ws = new WebSocket("ws://192.168.120.145:3000") //socket本地IP+端口
ws.addEventListener("open", () => {
ws.send(
JSON.stringify({
action: "login", //动作登录
id: 1, //用户ID
fingerprint: createBrowserFingerprint(), //浏览器指纹
})
)
})
ws.addEventListener("message", (message) => {
const data = JSON.parse(message.data)
if (data.action === "logout") {
alert(data.message) //监听到挤下线操作提示弹框
}
})
</script>
</body>
</html>
Preview

Nodejs Chapter 66 (SCL scan code login)
Scan the QR code to log in
SCL (Scan Code Login) is a scanning code login technology that allows users to log in by scanning a QR code. This login method is widely used in many apps and websites because it is simple, convenient, and secure.
The advantages of SCL scan code login include:
- Convenient and fast: Users only need to open the QR code scanning application and scan the QR code to complete the login, without manually entering the user name and password.
- High security: Scan code login uses encryption technology, and the user's login information is protected during the transmission process, reducing the risk of password theft or leakage.
- Avoid keylogging: Since users do not need to enter sensitive information such as username and password during the login process, they are not exposed to the threat of keylogging software.
- Wide applicability: SCL scan code login can be integrated with different applications and websites, providing a unified login method so that users do not need to remember user names and passwords for multiple accounts.
Implementation process
Installed dependencies
- express provides interface services
- jsonwebtoken generates token
- qrcode generates QR code
Flowchart

General logic
const status = {
0: "未授权",
1: "已授权",
2: "超时",
}
- A page is required to call the interface to obtain the QRcode, which is the QR code, for display, and then display the status by the way. The default is 0 (unauthorized).
- On this page, poll the interface to check whether the status is authorized. If it is authorized or times out, stop polling.
- After scanning the QR code, the authorization page will open. Click the confirmation button on the authorization page to authorize and distribute tokens.
Code implementation
Directory structure
public
- mandate.html authorization page
- qrcode.html QR code page
index.js nodejs logic code
index.js
import express from "express"
import qrcode from "qrcode"
import jwt from "jsonwebtoken"
let user = {}
let userId = 1 //模拟一个用户
const app = express()
app.use(express.json())
app.use("/static", express.static("public")) //初始化静态目录
//初始化数据结构 记录用户和创建二维码的时间
//并且生成二维码的时候使用的是授权的那个页面并且把用户id带过去
app.get("/qrcode", async (req, res) => {
user[userId] = {
token: null,
time: Date.now(),
}
const code = await qrcode.toDataURL(
`http://192.168.120.145:3000/static/mandate.html?userId=${userId}`
)
res.json({
code,
userId,
})
})
//授权确认接口 陈功授权之后生成token
app.post("/login/:userId", (req, res) => {
const token = jwt.sign(req.params.userId, "secret")
user[req.params.userId].token = token
user[req.params.userId].time = Date.now()
res.json({
token,
})
})
//检查接口 这个接口要被轮询调用检查状态,0未授权 1已授权 2超时
app.get("/check/:userId", (req, res) => {
//判断超时时间
if (Date.now() - user[userId].time > 1000 * 60 * 1) {
return res.json({
status: 2,
})
}
//如果有token那就是验证成功
else if (user[1].token) {
return res.json({
status: 1,
})
} else {
return res.json({
status: 0,
})
}
})
app.listen(3000, () => {
console.log("http://localhost:3000")
})
qrcode.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<img id="qrcode" src="" alt="" />
<div id="status-div"></div>
<script>
const status = {
0: "未授权",
1: "已授权",
2: "超时",
}
const qrcode = document.getElementById("qrcode")
const statusDiv = document.getElementById("status-div")
let userId = null
statusDiv.innerText = status[0]
fetch("/qrcode")
.then((res) => res.json())
.then((res) => {
qrcode.src = res.code //获取二维码
userId = res.userId //获取用户id
let timer = setInterval(() => {
//轮询调用检查接口
fetch(`/check/${userId}`)
.then((res) => res.json())
.then((res) => {
statusDiv.innerText = status[res.status]
//如果返回的状态是 超时 或者是已授权 就停止轮训
if (res.status != 0) {
clearInterval(timer)
}
})
}, 1000)
})
</script>
</body>
</html>
mandate.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div>
<button id="btn" style="width: 100%;height: 50px;">同意授权</button>
</div>
<div>
<button style="width: 100%;height: 50px;margin-top: 20px;">
拒绝授权
</button>
</div>
<script>
const btn = document.getElementById("btn")
let userId = location.search.slice(1).split("=")[1]
btn.onclick = () => {
//点击授权按钮
fetch(`/login/${userId}`, {
method: "POST",
})
.then((res) => res.json())
.then((res) => {
alert(`授权成功`)
})
.catch((err) => {
alert(err)
})
}
</script>
</body>
</html>
Effect preview

Nodejs Chapter 67 (OpenAI)
OpenAI
OpenAI is an artificial intelligence research laboratory and technology company dedicated to promoting the development and application of artificial intelligence
One of OpenAI's most famous projects is the GPT (Generative Pre-trained Transformer) series of models, which includes GPT-3, which is one of the largest language models to date. GPT-3 has amazing language generation and understanding capabilities and can perform various natural language processing tasks, such as text generation, translation, question answering, etc.

Application scenarios
Using Node.js and OpenAI API, you can implement various applications, such as:
- Text generation: Use OpenAI’s text generation capabilities to generate articles, stories, conversations and other content.
- Language translation: By calling the OpenAI API, the automatic translation function is realized and one language is translated into another language.
- Question answering: Pass the questions raised by users to the OpenAI model to obtain high-quality answers.
- Intelligent conversation robot: Build an intelligent conversation robot that can have natural and smooth conversations with users.
Application process
- Visit the openAI official website openai.com/
- Log in


Apply for key



Code writing
Dependencies that need to be installed
- dotenv gets environment variables
- openai calls openai capabilities
- Express writes interfaces to provide services
Create a new .env file
API-KEY = 'openai秘钥'
Create a new index.js file
import OpenAi from "openai"
import dontenv from "dotenv"
import express from "express"
const app = express()
app.use(express.json())
dontenv.config() //注册环境变量
const openAi = new OpenAi({
apiKey: process.env["API-KEY"], //读取秘钥
})
//文本对话
app.post("/chat", async (req, res) => {
const { message } = req.body //message就是你要问的问题
const completion = await openAi.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: message }],
})
res.json({
result: completion.choices[0].message.content, //返回信息
})
})
//生成图片
app.post("/create/image", async (req, res) => {
const { prompt } = req.body //你要描述的图片信息
const completion = await openAi.images.generate({
model: "dall-e-2", //使用的模型
prompt,
n: 1,
size: "1024x1024",
})
res.json({
result: completion.data[0].url, //返回图片地址
})
})
app.listen(3000, () => {
console.log("Server is running on port 3000")
})
Effect display


Nodejs Chapter 68 (Remote Desktop)
Remote Desktop
Remote Desktop is a technology that allows users to remotely connect to another computer through a network and control the operations of the remote computer on the local computer. Remote Desktop allows users to share their screen, keyboard, and mouse between computers in different locations as if they were sitting in front of the remote computer.
Application scenarios
- Remote Desktop
- Remote server operation
- Cloud gaming
Environment preparation
python environment installation

c++ environment installation
visualstudio.microsoft.com/zh-hans/tha…

Global dependencies
npm install node-gyp -g
Because robotjs needs to depend on c++ node-gyp depends on python and robotjs needs to be compiled through node-gyp
Project dependencies
- screenshot-desktop screenshot
- ws real-time transmission
- get-pixels gets the image size
- robotjs operates controlled devices
Code writing
nodejs side
The core idea is that screenshots are transmitted through ws. The specific transmission rate can be controlled by one second I set here. After the front-end receives it, it is displayed on the picture. The front-end clicks on the XY axis of the picture and transmits it to the server. The server simulates operations through robotjs.
import screenshot from "screenshot-desktop"
import { WebSocketServer } from "ws"
import http from "http"
import getPixels from "get-pixels"
import fs from "fs"
import path from "path"
import robot from "robotjs"
const createScreenshot = async () => {
const image = await screenshot({ format: "png" })
return {
base64: image.toString("base64"), //截图受控设备返回base64
imageBuffer: image, //返回buffer流
}
}
const server = http.createServer()
const wss = new WebSocketServer({ server }) //创建webSocket服务
const getScreenSize = async () => {
const { imageBuffer, base64 } = await createScreenshot()
const filePath = path.join(process.cwd(), "/screenshot.png")
fs.writeFileSync(filePath, imageBuffer) //将图片存入本地 一直替换
return new Promise((resolve, reject) => {
getPixels(filePath, (err, pixels) => {
if (err) reject(err)
resolve({
width: pixels.shape[0], //获取图片宽高
height: pixels.shape[1], //获取图片宽高
base64, //返回图片base64
})
})
})
}
wss.on("connection", async (ws) => {
ws.on("message", (message) => {
const data = JSON.parse(message)
if (data.type === "click") {
//监听事件
const x = data.x
const y = data.y
robot.moveMouse(x, y) //点击的位置
robot.mouseClick() //模拟点击事件
}
})
setInterval(async () => {
const data = await getScreenSize()
ws.send(JSON.stringify(data))
}, 1000) //一秒钟发送一次截图
})
server.listen(3000)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
img {
width: 100%;
height: 100%;
}
* {
margin: 0;
padding: 0;
}
</style>
</head>
<img id="img" src="" alt="" />
<body>
<script>
//如果你部署到服务器可以使用服务器的地址 我这里使用的windows 沙箱的ip
const ws = new WebSocket("ws://172.29.65.216:3000")
const image = document.getElementById("img")
ws.onmessage = (event) => {
const data = JSON.parse(event.data)
image.src = `data:image/png;base64,${data.base64}`
image.style.width = `${data.width}px`
image.style.height = `${data.height}px`
}
//传递事件 当然你也再加键盘什么的 我这儿举个例子
const hendler = (e) => {
e.preventDefault()
ws.send(
JSON.stringify({
type: e.type,
x: e.clientX,
y: e.clientY,
})
)
}
image.onclick = hendler
image.ondblclick = hendler
</script>
</body>
</html>
Effect demonstration

Nodejs Chapter 69 (Antivirus)
Antivirus
Antivirus refers to a type of computer security software designed to detect, block and remove malicious software in computer systems, such as viruses, worms, Trojans, spyware and adware. These malware may cause damage to computer systems and user data, including data loss, system crash, personal information leakage, etc.
Antivirus software protects computers from malware threats by using various techniques
Application scenarios
- Writing anti-virus software
- Daily antivirus use
- Real-time protection
- Email web scanning
- Server antivirus
Engine
ClamAV (Clam AntiVirus) is an open source cross-platform antivirus software that focuses on detecting and removing malware, including viruses, worms, Trojans, malware and other malicious code.
Here are some of ClamAV’s features and capabilities:
- Open source and free: ClamAV is a free and open source antivirus software that can be used for free on various operating systems, including Windows, macOS, and Linux.
- Multi-platform support: ClamAV is cross-platform and can run on a variety of operating systems, including Windows, macOS, Linux, FreeBSD, etc.
- Virus scanning engine: ClamAV uses a powerful virus scanning engine to detect and identify various malware. It can scan files, folders, compressed files, etc. for potential threats.
- Multiple scanning modes: ClamAV provides different scanning modes, including quick scan, full scan and customized scan. Users can select the appropriate scanning mode according to their needs.
- Real-time protection: ClamAV can provide real-time monitoring and protection capabilities, which can instantly detect and block potential malware when files are accessed, downloaded or executed.
- Virus definition updates: ClamAV regularly releases updates to the virus definition database to maintain the ability to identify emerging viruses and malware variants. Users can update virus definition files manually or automatically.
- Command line tools and graphical interface: ClamAV provides command line tools and graphical interface, allowing users to easily perform operations such as scanning, updating, and configuration.
Download and install
Select the corresponding operating system

windows
- After downloading, install and configure environment variables.
After the installation is complete, there will be a conf_examples folder in the directory that comes with it.
- clamd.conf
- freshclam.conf
Copy the contents of the folder to the root directory

Then comment out Example in these two files

- Update virus database
Execute this command freshclam

Start clamd service

nodejs use
Install clamscan
npm install clamscan
import NodeClam from "clamscan"
const clam = new NodeClam().init({
scanRecursively: true, //深度扫毒
clamdscan: {
port: 3310, //连接引擎的端口 端口配置项在这个文件 clamd.conf 默认3310
host: "localhost", //连接引擎的IP
},
clamscan: {
scanArchives: true, //扫描归档文件
scanFiles: true, //扫描文件
},
})
clam.then((clamscan) => {
//批量扫描文件
clamscan.scanFiles(
["./index.js", "./package.json", "./package-lock.json"],
(err, goodfiles, badfiles) => {
if (err) {
console.log(err)
} else {
console.log("扫描完成")
//goodfiles 就是没问题的文件
//badfiles 就是病毒文件
console.log(goodfiles, badfiles)
}
}
)
//扫描目录
clamscan.scanDir("./", (err, goodfiles, badfiles) => {
if (err) {
console.log(err)
} else {
console.log("扫描完成")
console.log(goodfiles, badfiles)
}
})
//检查是否是病毒文件
clamscan.isInfected("./index.js", (err, result) => {
if (err) {
console.log(err)
} else {
console.log(result)
}
})
})
Demo
Scan three files
clamscan.scanDir This method cannot be used in Windows and can only be used in Linux.

Nodejs Chapter 70 (OSS)
OSS
OSS (Object Storage Service) is a cloud storage service that provides a highly scalable, safe and reliable object storage solution
OSS object storage uses objects as the basic storage unit, and each object has a unique identifier (called an object key) and data. These objects can be any type of file, such as documents, pictures, videos, etc. OSS provides high availability, high scalability and high security storage services, suitable for various application scenarios, including data backup and archiving, static website hosting, large-scale data processing, mobile application storage, etc.
When our computers are usually developed, they are stored in files and folders.

- OSS is stored according to
Bucket

OSS purchase (Alibaba Cloud demo)
- Buy a 40G resource package for $4.98 yuan

- Create a
Bucketafter purchasing
Select public reading. If you select private, you need to bring the private key when accessing the picture.

- Test uploading pictures

Just access it directly

NodejsUpload
Create a secret key nodejs needs to use

npm install ali-oss
import OSS from "ali-oss"
import path from "node:path"
const client = new OSS({
region: "oss-cn-beijing", //区域
accessKeyId: "XXXXXXXXXXXXXXXXXXXX上图的accessKeyId",
accessKeySecret: "XXXXXXXXXXXXXXXXX上图的accessKeySecret",
bucket: "nodejs-oss", //存储库
})
upload
//第一个参数上传到OSS文件的名称
//第二个参数本地图片的路径
const result = await client.put("1.jpg", "./1.jpg")
console.log(result)
Download
//第一个参数OSS图片名称
//第二个参数下载到本地的路径
await client.get("1.png", path.join(process.cwd(), "./1.png"))
Delete
//第一个参数删除存储库文件的名称
const result = await client.delete("1.png")
Third-party authorization
import OSS from "ali-oss"
import express from "express"
import path from "node:path"
import cors from "cors"
const app = express()
app.use(cors())
const config = {
region: "oss-cn-beijing",
accessKeyId: "XXXXXXXX",
accessKeySecret: "XXXXXXXX",
bucket: "nodejs-oss",
}
const client = new OSS(config)
app.get("/", async (req, res) => {
const date = new Date()
date.setDate(date.getDate() + 1)
const policy = {
expiration: date.toISOString(), //设置签名日期
conditions: [
["content-length-range", 0, 1048576000], //设置文件大小限制
],
}
const formData = await client.calculatePostSignature(policy)
const { location } = await client.getBucketLocation()
const host = `http://${config.bucket}.${location}.aliyuncs.com`
res.json({
host, //返回上传的url
policy: formData.policy, //返回政策
OSSAccessKeyId: formData.OSSAccessKeyId, //返回秘钥
signature: formData.Signature, //返回签名
})
})
app.listen(3000, () => {
console.log("server is running on port 3000")
})
Front-end upload
Call the backend interface to get the parameters that need to be uploaded and pass them to the Alibaba Cloud interface.
Remember to set cross-domain

const file = document.getElementById("file")
let params = {}
fetch("http://localhost:3000/")
.then((res) => res.json())
.then((res) => {
params = res
})
file.addEventListener("change", (e) => {
let file = e.target.files[0]
const formData = new FormData()
formData.append("key", file.name)
formData.append("policy", params.policy)
formData.append("OSSAccessKeyId", params.OSSAccessKeyId)
formData.append("success_action_status", 200)
formData.append("signature", params.signature)
formData.append("file", file)
fetch(params.host, {
method: "POST",
body: formData,
})
})
Effect preview

Nodejs Chapter 71 (libuv)
libuv
In Node.js, libuv exists as the core component of its event loop and asynchronous I/O. Node.js is built on libuv, which uses libuv to handle underlying Step, such as file I/O, network communication, and timers.
libuv plays the following important roles in Node.js:
- Event Loop: libuv implements
Event Cycle Mechanismof Node.js and is responsible for managing the scheduling and execution of events. The event loop is the core mechanism of Node.js, which enables Node.js to handle a large number of concurrent operations in a non-blocking manner. - Asynchronous I/O operations: libuv provides a set of asynchronous I/O APIs for processing files, networks, and other I/O operations. These APIs can operate in the background without blocking the main thread, enabling efficient concurrent processing.
- Network communication: libuv encapsulates the underlying network communication functions, including the creation, binding, monitoring and connection of TCP and UDP sockets. It provides an advanced network interface to facilitate developers to build network-based applications.
- Timer and event triggering: libuv provides timer-related APIs, which can create and manage timers, and trigger corresponding callback functions after a specified time interval. This is very useful for handling scheduled tasks and scheduling.
- Cross-platform support: libuv implements abstract encapsulation of different operating systems, allowing Node.js to run on different platforms and maintain consistent behavior and performance.
Event loop
nodejs official website event loop description
In Nodejs, the event loop is divided into 6 phases. Each stage has a task queue. When Node starts, an event loop thread will be created, and it will enter each stage in the order shown in the figure below and execute the callbacks of each stage.

Nodejs event loop can be divided into two types, Micro and Macro
macro task
- timers
Execute settimeout and setInterval - pending callbacks
Executing delayed return like IO, timer - idle, prepare idle state
Nodejs in-house use without concern - poll
Execution of I/O-related calls (almost all callbacks are executed except for closing off, timer scheduling and setImmediate) e.g. fs's callback http://www.ffs.com Rewind - check
Execute the setImmediate echo - close callback
Execute echoes for example socket.on ('close',...)
microtasks
- process.nextTick
- promise
Note: Inaccurate timer
We write a case Output 3, 1, 2, not 1, 2, 3. according to the above sequence

The official website explains this reason because, in each loop iteration of the event loop, libuv will call the uv__update_time function to update the current timestamp. This timestamp is usually used to calculate the timeout of the timer and check the occurrence time of the event. setImmediate inserts the callback function directly into the queue, so the execution efficiency is relatively high. This will cause sequence instability.
Analyze source code
libuv/src/unix/core.c
int uv_run(uv_loop_t* loop, uv_run_mode mode) {
int timeout;
int r;
int can_sleep;
r = uv__loop_alive(loop); //检查事件循环是否活跃
if (!r) //如果事件循环不活跃,直接返回
uv__update_time(loop); //调用这个函数更新时间戳去检查计时器 超时时间 耗时
/* Maintain backwards compatibility by processing timers before entering the
* while loop for UV_RUN_DEFAULT. Otherwise timers only need to be executed
* once, which should be done after polling in order to maintain proper
* execution order of the conceptual event loop. */
if (mode == UV_RUN_DEFAULT && r != 0 && loop->stop_flag == 0) {
uv__update_time(loop); //更新时间
uv__run_timers(loop); //执行定时器
}
while (r != 0 && loop->stop_flag == 0) {
can_sleep =
uv__queue_empty(&loop->pending_queue) &&
uv__queue_empty(&loop->idle_handles);
uv__run_pending(loop); //执行事件队列中的事件
uv__run_idle(loop); //执行空闲队列中的事件
uv__run_prepare(loop); //执行预备队列中的事件
timeout = 0;
if ((mode == UV_RUN_ONCE && can_sleep) || mode == UV_RUN_DEFAULT)
timeout = uv__backend_timeout(loop);
uv__metrics_inc_loop_count(loop);
uv__io_poll(loop, timeout); //执行事件循环
/* Process immediate callbacks (e.g. write_cb) a small fixed number of
* times to avoid loop starvation.*/
for (r = 0; r < 8 && !uv__queue_empty(&loop->pending_queue); r++)
uv__run_pending(loop);
/* Run one final update on the provider_idle_time in case uv__io_poll
* returned because the timeout expired, but no events were received. This
* call will be ignored if the provider_entry_time was either never set (if
* the timeout == 0) or was already updated b/c an event was received.
*/
uv__metrics_update_idle_time(loop); //更新空闲时间
uv__run_check(loop); //执行检查队列中的事件 setImmediate
uv__run_closing_handles(loop); //执行关闭队列中的事件
uv__update_time(loop); //更新时间
uv__run_timers(loop); //执行定时器
r = uv__loop_alive(loop);
if (mode == UV_RUN_ONCE || mode == UV_RUN_NOWAIT)
break;
}
libuv/src/unix/internal.h
uv update time
UV_UNUSED(static void uv__update_time(uv_loop_t* loop)) {
/* Use a fast time source if available. We only need millisecond precision.
*/
// 这个函数通过调用 `gethrtime` 获取系统当前时间,精度非常高,单位是纳秒(ns),
// 1 纳秒等于十亿分之一秒。除 `1000000` 后的时间单位为 毫秒(ms)
loop->time = uv__hrtime(UV_CLOCK_FAST) / 1000000;
}
Notes Microtasks
Different versions of nodejs have different microtask execution strategies
Lower version nextTick takes precedence over Promise
nodejs V10 test

nodejs V20 test

Nodejs Chapter 72 (fastify)
fastify
Fastify is a web framework that is highly focused on providing the best development experience with minimal overhead and a powerful plugin architecture. It is inspired by Hapi and Express, one of the Fastest web frameworks that runs on Node.js.
Fastify can be regarded as an efficient and modern web framework in Node.js and is an excellent choice for building fast web applications.
fastify features
- High Performance: As far as we know, Fastify is one of the fastest web frameworks and we can handle up to
40,000requests per second depending on the code complexity. - Extensible: Fastify is fully extensible through its hooks, plugins and decorators.
- Schema-based: Although not mandatory, we recommend using JSON Schema to validate your routes and serialize your output. Fastify internally compiles the schema into a high-performance function.
- Logging: Logging is important but costly; we chose Pino, the best logger, to virtually eliminate this cost!
- Developer Friendly: This framework is designed to be very expressive and help developers in daily use without sacrificing performance and security.
- TypeScript Ready: We work hard to maintain TypeScript type declaration files
Comparison between Fastify and other frameworks

Application scenarios
- Gateway layer
- One of the only frameworks in Nest
- Require high-performance services
- Ethereum
Basic usage
Basically the same as express
import fastify from "fastify"
const server = fastify()
//post接口
server.post("/", async (request, reply) => {
const { name, version } = request.body
//返回json 支持直接return
return {
name,
version,
}
})
//get接口
server.get("/", async (request, reply) => {
reply.send(`${request.query.name}`)
})
server.listen({ port: 3000 }).then(() => console.log("server is running"))
Routing
- method defines the request method, such as get post put, etc.
- url matches interface path
- schema object containing request and response patterns. They need to be in the format
JSON Structure
- body verifies the parameters of the post interface
- querystring verifies the parameters above the address bar, which is get
- params validates dynamic parameters
- response filters and generates response patterns. Setting the pattern can increase our throughput by 10-20%
- handler request processing function
server.route({
method: "GET",
url: "/list",
schema: {
querystring: {
type: "object",
properties: {
page: { type: "number" },
pageNo: { type: "number" },
},
required: ["page", "pageNo"], //必填项
},
response: {
200: {
type: "object", //返回一个对象
properties: {
//返回的数属性描述
data: {
//返回data
type: "array", //是个数组类型
items: {
//子集
type: "object", //是个对象
properties: {
//子集的属性
name: { type: "string" },
version: { type: "string" },
},
},
},
},
},
},
},
handler: (request, reply) => {
request.query.page
return {
data: [{ name: "fastify", version: "4.27.0" }],
}
},
})
Plug-in writing
Like JavaScript, everything is an object, in Fastify everything is a plugin
Fastify allows users to extend its functionality through plugins. A plugin can be a set of routes, a server decorator, or anything else. The API you need to use one or more plugins is register.
fastify.register(plugin, [options])
- app is a fastify instance
- options are the passed parameters
- done control flow is the same as express next
import Fastify from "fastify"
const app = Fastify()
server.register(
function (fastify, opts, done) {
app.decorate(opts.name, (a, b) => a + b)
const res = app.add(1, 2)
console.log(res)
done()
},
{
name: "add", //options
}
)
Connect to database
Fastify’s ecosystem provides a number of plugins for connecting to various database engines.
fastify.dev/ecosystem/ You can go to Ecosystem to find any plug-ins you need.
Installation package
npm i @fastify/mysql
Connect to database
server.register(import("@fastify/mysql"), {
connectionString: "mysql://root:123456@localhost:3306/xiaoman", //账号,密码,IP,端口,库名
})
Implement a simple add and query
import fastify from "fastify"
const server = fastify({
logger: false,
})
server.register(import("@fastify/mysql"), {
connectionString: "mysql://root:123456@localhost:3306/xiaoma",
})
//添加
server.post("/add", (request, reply) => {
server.mysql.query(
"insert into user(create_time,name,hobby) values(?,?,?)",
[new Date(), request.body.name, request.body.hobby],
(err, results) => {
if (err) {
console.log(err)
return reply.send(err)
}
reply.send({ results })
}
)
})
//查询
server.get("/list", (request, reply) => {
server.mysql.query("select * from user", (err, result) => {
reply.send({ result })
})
})
server.listen({ port: 3000 }).then(() => console.log("server is running"))
Nodejs Chapter 73 (Gateway Layer)
What is the gateway layer?
Technology selection fastify is fast and suitable for the gateway layer. It is mentioned in the previous chapter of the fastify tutorial.
The gateway layer is the middle layer between the client and the backend service that handles and forwards requests. It acts as the entry point for requests and is responsible for routing requests to the appropriate backend service and returning responses from the backend service to the client. The gateway layer plays a key role in distributed systems and microservice architectures.
Here are some of the key features and benefits of the gateway layer:
- Routing: The gateway layer can forward requests to different backend services based on the requested URL path or other conditions. It can decide which service the request should be sent to for processing based on specific routing rules.
- Load Balancing: When there are multiple back-end services providing the same functions, the gateway layer can distribute requests to these services through the load balancing algorithm to achieve the purpose of distributing the load and improving system performance and availability.
- Caching and performance optimization: The gateway layer can cache some frequently requested data or responses to reduce the load on back-end services and improve response speed. By caching static content or frequently requested data, you can reduce requests to backend services, thereby improving overall performance.
- Channel Encryption: The gateway layer can provide encryption and decryption functions for request and response data to ensure the security and confidentiality of data during transmission. By using encryption algorithms and security certificates, the gateway layer protects sensitive data from unauthorized access and eavesdropping.
- Circuit breaker technology: When the backend service fails or is abnormal, the gateway layer can use circuit breaker technology to prevent requests from continuing to be sent to the problematic service. By monitoring the status and performance indicators of back-end services, the gateway layer can automatically switch to backup services or return error responses to improve system fault tolerance and reliability.
- Current Limiting: The gateway layer can implement request limiting policies to prevent overload caused by excessive requests to back-end services. The gateway layer protects backend services from abuse or malicious attacks by limiting the request rate per client or the total number of requests.
Install dependencies
npm install fastify
npm install express
npm install @fastify/caching #缓存
npm install @fastify/http-proxy #代理/负载均衡
npm install @fastify/rate-limit #限流
npm install opossum #熔断技术
Directory structure
src / config / index.js
proxy / index.js
index.js
package.json
server.js
First write the outer server.js to start a simple service
process.argv[2] uses process here to accept the port number so that multiple services can be easily opened.
import express from "express"
const app = express()
app.get("/info", (req, res) => {
res.json({
code: 200,
port: process.argv[2],
})
})
app.get("/", (req, res) => {
res.json({
code: 200,
})
})
app.listen(process.argv[2], () =>
console.log(`Server running on port ${process.argv[2]}`)
)
Start service
node server.js 9001
node server.js 9002
Gateway layer writing
src/index.js
Core function implementation
- Proxy service (the configuration item of the proxy service is an array and is registered cyclically, so that the entrance can be unified)
- Melting technology (detects whether the service is running normally, and fuses if it hangs up or times out a certain threshold)
- Caching technology (the bottom layer is actually
Consultation Cache|Strong Cache) - Current limiting technology (stipulates that only a few requests can be initiated within a certain period of time to prevent DDOS)
Warm reminder: You do not have to follow my implementation, it is just a reference. In general scenarios, these functions need to be implemented.
import fastify from "fastify"
import proxy from "@fastify/http-proxy" //负载代理技术
import rateLimit from "@fastify/rate-limit" //限流技术
import proxyConfig from "./proxy/index.js" //请往下翻
import caching from "@fastify/caching" //缓存技术
import CircuitBreaker from "opossum" //熔断技术
import {
rateLimitConfig,
cachingConfig,
breakerConfig,
} from "./config/index.js" //请往下翻
const app = fastify({
logger: false,
})
//熔断技术
const breaker = new CircuitBreaker((url) => {
return fetch(url).then((res) => res.json()) //检测服务是否挂掉
}, breakerConfig)
app.register(caching, cachingConfig) //注册缓存服务
app.register(rateLimit, rateLimitConfig) //注册限流
proxyConfig.forEach(({ upstream, prefix, rewritePrefix, httpMethods }) => {
app.register(proxy, {
//请求代理服务之前触发熔断
preHandler: (request, reply, done) => {
//检测这个服务 如果服务挂掉立马熔断
breaker
.fire(upstream)
.then(() => done())
.catch(() => reply.code(503).send("Circuit breaker tripped"))
},
upstream,
prefix,
rewritePrefix,
httpMethods,
})
})
//启动服网关
app
.listen({ port: 3000 })
.then(() => console.log("server running on port 3000"))
proxy/index.js
Proxy service configuration file

Our system can also implement multiple gateway layers depending on the device
Warm reminder: There is not necessarily only one gateway layer.
export default [
{
upstream: "http://localhost:9001", //代理地址
prefix: "/pc", //前缀
rewritePrefix: "", //实际请求将pc 替换成 '' 因为后端服务器没有pc这个路由
httpMethods: ["GET", "POST"], //允许的请求方式
},
{
upstream: "http://localhost:9002",
prefix: "/mobile",
rewritePrefix: "",
httpMethods: ["GET", "POST"],
},
]
config/index.js
Other configuration items
export const rateLimitConfig = {
max: 5, //每 1 分钟最多允许 5 次请求
timeWindow: "1 minute", //一分钟
}
export const cachingConfig = {
privacy: "private", //缓存客户端服务器 禁止缓存代理服务器
expiresIn: 1000, //缓存1s
}
export const breakerConfig = {
errorThresholdPercentage: 40, //超过 40% 会触发熔断
timeout: 1000, //超过 1s 会触发熔断
resetTimeout: 5000, //熔断后 5s 会重置
}
Start service
nodemon src/index.js
Nodejs Chapter 74 (Microservices)
What are microservices?
micro servers
Microservices are similar to microfrontends. Microfrontends are implemented based on the concept of microservices. Microservices refer to splitting the application into a series of small, independent services. Each service is focused on executing specific businesses. For example, the article's service executes the article's logic and the user's service executes the user's logic. These services can be developed, tested, deployed and expanded independently, and can communicate.
Monolithic architecture vs microservice architecture
- The monolithic architecture is suitable for small projects with low concurrency (
5-10w). In fact, all functions are put into one project. - The microservice architecture is suitable for large projects with high concurrency, that is, each module is split into a small project so that it can be deployed independently
Intuitive diagram Monolithic architecture on the left Microservice architecture on the right

Architecture implementation

Advantages of microservices
- Independent deployment: Each microservice can be deployed independently. This means that when a service needs to be updated or fixed, only that service needs to be redeployed, rather than the entire application.
- Technology diversity: Microservice architecture allows different microservices to use different technology stacks and programming languages. In this way, the most suitable technology can be selected according to specific needs and improve development efficiency and flexibility.
- Elastic expansion: Since each microservice is independent, each service can be expanded independently according to actual needs. This allows the system to better cope with traffic peaks and increased load, improving system scalability and availability.
Who is using nodejs to build microservices?
- Netflix
- Uber
- Taobao
- Tencent Video
- Meituan Group Buying
- JD order management
Microservice construction
Tips do not have to be constructed in the same way as mine. I am just giving an example. There is no fixed implementation method and can be adjusted according to your own business.
The currently popular monorepo architecture means multiple projects use one warehouse.
Requires pnpm support
npm install pnpm -g
Directory structure
app/
├── common/
│ └── index.ts
├── packages/
│ ├── gateway/ //其实这就是一个单独的项目
│ │ ├── index.ts
│ │ └── package.json
│ ├── user/ //其实这就是一个单独的项目
│ │ ├── index.ts
│ │ └── package.json
│ └── post/ //其实这就是一个单独的项目
│ ├── index.ts
│ └── package.json
├── tsconfig.json
├── pnpm-workspace.yaml
├── package.json
Configure monorepo support and create a new root directory pnpm-workspace.yaml
packages:
- 'packages/*'
- 'common
execute
pnpm install #就会自动安装common目录里面的依赖 和packages目录下面的所有的依赖都会安装
Microservices will also have point-to-point communication between multiple services. This is the top priority. The next chapter will talk about the core knowledge of communication between microservices.
Nodejs Chapter 75 (MQ)
What is RabbitMQ?
- RabbitMQ is an open source, complete, reusable enterprise messaging system based on AMQP.
- Supports mainstream operating systems, Linux, Windows, MacOS, etc.
- Multiple development language support, Java, Python, Ruby, .NET, PHP, C/C++, javaScript, etc.
AMQP (Advanced Message Queuing Protocol) implements message sorting, point-to-point communication, and publish and subscribe, maintaining reliability and ensuring security.
RabbitMQ core concepts
- Message: In RabbitMQ, message is the basic unit of delivery. It consists of a message body and optional attributes
- Producer: The producer is the sender of the message, which sends the message to the RabbitMQ exchange (Exchange)
- Exchange: The exchange receives messages sent from producers and routes the messages to one or more queues according to specific rules.
- Queue: The queue is the receiver of messages, which stores messages to be processed. Consumers can get messages from the queue and process them
- Consumer Consumer: The consumer is the receiver of the message. It obtains the message from the queue and processes it.

Installation of RabbitMQ
1. Rabbit MQ’s dependency environment erlang
Because MQ is developed based on this language
Download erlang from the official website: www.erlang.org/downloads

After the installation is complete, add an environment variable

ERLANG_HOME -> Corresponding directory such as (D:\erlang\Erlang OTP)
Then add path %ERLANG_HOME%\bin

Save, open cdm and enter erl. It will succeed without any error.

2. Install MQ

For example windows

Configure environment variables after installation is complete

Start MQ
Install the MQ plug-in to have a visualization panel
rabbitmq-plugins enable rabbitmq_management

Start MQ command
MQ default port 5672
rabbitmq-server.bat start

Visit http://localhost:15672/#/, the account password is guest

Nodejs use
We use MQ in Nodejs for nothing more than microservice applications or cross-language communication.
Install dependencies
npm install amqplib
producer.js producer
import express from "express"
import amqplib from "amqplib"
const app = express()
//连接MQ
const connection = await amqplib.connect("amqp://localhost")
//创建一个通道
const channel = await connection.createChannel()
const queueName = "task_queue"
app.get("/send", (req, res) => {
const message = req.query.message
//发送消息
channel.sendToQueue(queueName, Buffer.from(message), {
persistent: true, //持久化消息
})
res.send("send message success")
})
app.listen(3000, () => {
console.log("producer listen 3000")
})
consume.js consumer
import amqplib from "amqplib"
const queueName = "task_queue"
//连接
const connection = await amqplib.connect("amqp://localhost")
const channel = await connection.createChannel()
//连接队列
await channel.assertQueue(queueName, {
durable: true, //队列持久化
})
//消息者监听器
channel.consume(queueName, (msg) => {
console.log(`[x] Received ${msg.content.toString()}`)
channel.ack(msg) //确认消费该消息
})
Persistence implementation
The producer pushed the message into the queue and went down. After restarting, the message was lost. In order to solve this problem, we need to implement a persistence strategy.
- Queue persistence
Starts the queue when the consumer connects: true - Message persistence
Sender opens the message when sending
It can even communicate across languages python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
queueName = 'task_queue'
channel.queue_declare(queue=queueName,durable=True)
message = '小满zs'
channel.basic_publish(exchange='',routing_key=queueName,body=message)
connection.close()
Application scenarios
- Communication between microservices, or cross-language level communication
- Asynchronous tasks, such as completing an interface and sending an email. We do not need to wait for the email to be sent before returning. We can directly return the result and process the email in the asynchronous task.
- Log collection and distribution, send the application's log messages to the RabbitMQ queue, and then use consumers for processing and distribution. This allows centralized management and processing of logs, providing real-time monitoring and analysis
Effect display

Nodejs Chapter 76 (MQ Advanced)

The introduction and basic use of MQ have been introduced in the previous chapter and will not be repeated juejin.cn/post/737508…
- Message: In RabbitMQ, message is the basic unit of delivery. It consists of a message body and optional attributes
- Producer: The producer is the sender of the message, which sends the message to the RabbitMQ exchange (Exchange)
- Exchange: The exchange receives messages sent from producers and routes the messages to one or more queues according to specific rules.
- Queue: The queue is the receiver of messages, which stores messages to be processed. Consumers can get messages from the queue and process them
- Consumer Consumer: The consumer is the receiver of the message. It obtains the message from the queue and processes it.

Advanced usage of MQ
publishsubscribe
Publish and subscribe, the sender of the message is called the publisher (Publisher), and the one or more entities that receive the message are called subscribers (Subscriber)
Looking back at the previous article, the point-to-point communication producer sends a message to the Queue through routing, and only one consumer can consume it, that is, One on one. sends

Return to the topic Publish and subscribe means that the producer's messages are written to multiple queues through the switch, and different subscribers consume different queues, which is to implement More pairs.

There are four modes of publish and subscribe
- Direct mode: Put the message into the queue designated by the switch
key. - Topic mode: Put the message into the queue specified by the switch
key. In addition, use "*" to match one word or use "#" to match multiple words. - Headers mode: put the message into the switch header attribute to match the queue
- Fanout (broadcast) mode: put the message into all queues of the switch to realize broadcast
Publish and subscribe-code writing
1. Writing in direct mode
The main purpose is to implement routing through routingKey matching. The zs here is the routingKey.
producer
import amqplib from "amqplib"
const connection = await amqplib.connect("amqp://localhost:5672")
//创建一个频道
const channel = await connection.createChannel()
//声明一个交换机
/**
* @param {String} exchange 交换机的名称
* @param {String} type "direct" | "topic" | "headers" | "fanout" | "match" | 使用广播模式
* @param {Object} options {durable: true} //开启消息持久化
*/
await channel.assertExchange("logs", "direct", {
durable: true,
})
//发送消息
/**
* @param {String} exchange 交换机的名称
* @param {String} routingKey 路由键
* @param {Buffer} content 消息内容
*/
//这里的zs就是routingKey
channel.publish("logs", "zs", Buffer.from("小满direct模式发送的消息"))
//断开
await channel.close()
await connection.close()
process.exit(0)
Consumer (we write multiple convenience tests)
consume.js
import amqplib from "amqplib"
const connection = await amqplib.connect("amqp://localhost:5672")
const channel = await connection.createChannel() //创建一个频道
await channel.assertExchange("logs", "direct", {
durable: true,
})
//添加一个队列
const { queue } = await channel.assertQueue("queue1", {
durable: true,
})
//绑定交换机
/**
* @param {String} queue 队列名称
* @param {String} exchange 交换机名称
* @param {String} routingKey 路由键
*/
//匹配对应的zs值才能收到
await channel.bindQueue(queue, "logs", "zs")
//接收消息
channel.consume(
"queue1",
(msg) => {
console.log(msg.content.toString())
},
{
noAck: true, //自动确认消息被消费
}
)
consume2.js
import amqplib from "amqplib"
const connection = await amqplib.connect("amqp://localhost:5672")
const channel = await connection.createChannel() //创建一个频道
await channel.assertExchange("logs", "direct", {
durable: true,
})
//添加一个队列
const { queue } = await channel.assertQueue("queue2", {
durable: true,
})
//绑定交换机
/**
* @param {String} queue 队列名称
* @param {String} exchange 交换机名称
* @param {String} routingKey 路由键
*/
//匹配对应的zs值才能收到
await channel.bindQueue(queue, "logs", "zs")
//接收消息
channel.consume(
"queue2",
(msg) => {
console.log(msg.content.toString())
},
{
noAck: true, //自动确认消息被消费
}
)
2. Topic mode writing
We switched the mode to Topic and changed the routingKey to xm.xxxxxxxx when publishing.
producer
import amqplib from "amqplib"
const connection = await amqplib.connect("amqp://localhost:5672")
//创建一个频道
const channel = await connection.createChannel()
//声明一个交换机
/**
* @param {String} exchange 交换机的名称
* @param {String} type "direct" | "topic" | "headers" | "fanout" | "match" | 使用广播模式
* @param {Object} options {durable: true} //开启消息持久化
*/
await channel.assertExchange("topic", "topic", {
durable: true,
})
//发送消息
/**
* @param {String} exchange 交换机的名称
* @param {String} routingKey 路由键
* @param {Buffer} content 消息内容
*/
//注意这儿匹配规则换了 换成xm.xxxxxxxxxxxxxxxxxxxxx
channel.publish(
"logs",
"xm.sadsdsdasdasdasdsda",
Buffer.from("小满topic模式发送的消息")
)
//断开
await channel.close()
await connection.close()
process.exit(0)
Consumer matching (note that the matching rule xm.*' uses *, which means fuzzy matching)
import amqplib from "amqplib"
const connection = await amqplib.connect("amqp://localhost:5672")
const channel = await connection.createChannel() //创建一个频道
await channel.assertExchange("topic", "topic", {
durable: true,
})
//添加一个队列
const { queue } = await channel.assertQueue("queue1", {
durable: true,
})
//绑定交换机
/**
* @param {String} queue 队列名称
* @param {String} exchange 交换机名称
* @param {String} routingKey 路由键 *匹配一个单词 #匹配多个单词
*/
//这儿变化了
await channel.bindQueue(queue, "topic", "xm.*")
//接收消息
channel.consume(
"queue1",
(msg) => {
console.log(msg.content.toString())
},
{
noAck: true, //自动确认消息被消费
}
)
3. Headers mode
Producer (note that publish adds a fourth parameter to enable the header and adds a data parameter)
import amqplib from "amqplib"
const connection = await amqplib.connect("amqp://localhost:5672")
//创建一个频道
const channel = await connection.createChannel()
//声明一个交换机
/**
* @param {String} exchange 交换机的名称
* @param {String} type "direct" | "topic" | "headers" | "fanout" | "match" | 使用广播模式
* @param {Object} options {durable: true} //开启消息持久化
*/
await channel.assertExchange("headers", "headers", {
durable: true,
})
//发送消息
/**
* @param {String} exchange 交换机的名称
* @param {String} routingKey 路由键
* @param {Buffer} content 消息内容
* @param {Object} options {headers: {'key': 'value'}} //定义匹配规则
*/
//嘿 这儿变了
channel.publish("headers", "", Buffer.from("小满headers模式发送的消息"), {
headers: {
data: "xmzs",
},
})
//断开
await channel.close()
await connection.close()
process.exit(0)
Consumer (bindQueue just adds an object whose attributes correspond to the producer)
import amqplib from "amqplib"
const connection = await amqplib.connect("amqp://localhost:5672")
const channel = await connection.createChannel() //创建一个频道
await channel.assertExchange("headers", "headers")
//添加一个队列
const { queue } = await channel.assertQueue("queue1")
//绑定交换机
/**
* @param {String} queue 队列名称
* @param {String} exchange 交换机名称
* @param {String} routingKey 路由键 *匹配一个单词 #匹配多个单词
*/
await channel.bindQueue(queue, "headers", "", {
data: "xmzs", //注意这儿不加headers 直接放值即可
})
//接收消息
channel.consume(
queue,
(msg) => {
console.log(msg.content.toString())
},
{
noAck: true, //自动确认消息被消费
}
)
4. Fanout mode
Producer (actually, the routingKey becomes a null value to implement global broadcast)
import amqplib from "amqplib"
const connection = await amqplib.connect("amqp://localhost:5672")
//创建一个频道
const channel = await connection.createChannel()
//声明一个交换机
/**
* @param {String} exchange 交换机的名称
* @param {String} type "direct" | "topic" | "headers" | "fanout" | "match" | 使用广播模式
* @param {Object} options {durable: true} //开启消息持久化
*/
await channel.assertExchange("fanout", "fanout")
//发送消息
/**
* @param {String} exchange 交换机的名称
* @param {String} routingKey 路由键
* @param {Buffer} content 消息内容
*/
channel.publish("fanout", "", Buffer.from("小满fanout模式发送的消息"))
//断开
await channel.close()
await connection.close()
process.exit(0)
Consumer (routingKey can accept null value, even if there is a value, it will be ignored)
import amqplib from "amqplib"
const connection = await amqplib.connect("amqp://localhost:5672")
const channel = await connection.createChannel() //创建一个频道
await channel.assertExchange("fanout", "fanout")
//添加一个队列
const { queue } = await channel.assertQueue("queue1")
//绑定交换机
/**
* @param {String} queue 队列名称
* @param {String} exchange 交换机名称
* @param {String} routingKey 路由键 *匹配一个单词 #匹配多个单词
*/
await channel.bindQueue(queue, "fanout", "")
//接收消息
channel.consume(
queue,
(msg) => {
console.log(msg.content.toString())
},
{
noAck: true, //自动确认消息被消费
}
)
Summary
Avoid the risk of database service crashes by using RabbitMQ as a buffer. The producer puts the message into the queue, the consumer reads the message from the queue, processes it, and then confirms that the message has been processed. When there is a one-to-many relationship between applications, an Exchange switch can be used to forward messages to the corresponding queue according to different rules:
- Direct exchange: forwards messages directly to a specific queue based on the routing key of the message.
- Topic exchange: performs fuzzy matching based on the routing key of the message and forwards the message to the queue that meets the conditions.
- Headers exchange: Forward based on the header information of the message.
- Broadcast switch (fanout exchange): broadcast the message to all queues under the switch
Effect demonstration

Nodejs Chapter 77 (MQ Advanced)
The introduction and basic use of MQ have been introduced in Chapter 75 and will not be repeated juejin.cn/post/737508…
MQ Advanced Usage-Delayed Message
What is a delayed message?
The Producer sends the message to the MQ server, but does not expect the message to be delivered immediately. Instead, it delays it for a certain period of time before delivering it to the Consumer for consumption. This message is a delayed message.
Plug-in installation
RabbitMQ delay queue plug-in download
Download address github.com/rabbitmq/ra…

Installation
Drag the downloaded file into the plugins directory under your rabbitMQ
#举例
D:\Applaaction\rabbitmq_server-3.13.0\plugins

Enable plugin
Execute the following command
rabbitmq-plugins enable rabbitmq_delayed_message_exchange

Check if successful
Open the visualization panel (How to install the visualization panel is explained in Chapter 75)
Visit http://localhost:15672/#/, the account password is guest
Found a new delay queue type x-delayed-message

Code writing
Application scenarios

It is now 2024-06-06 at 1.08 in the middle of the night. I chose to make a takeaway reservation for 11.00 - 11.20 at noon. If I choose to place an order for takeout, the order will not be pushed to the merchant's client immediately, but will be stored in the message queue. Using Delay Message, the order will be pushed to the merchant's client at a similar time period, such as around 10.30. In this way, it takes 10 minutes for the merchant to deliver the meal, and 20-30 minutes for the rider to deliver it. It will be delivered around 11 o'clock.
producer
The publish-subscribe model has been discussed in the previous chapter. If you don’t understand, go to the previous chapter.
- Let’s use the new delay type to switch the type
x-delayed-message - When connecting to the switch, add
Objectsand addx-delayed-type. The target switch type usesdirecthere. - Add header information
x-delay: time delay (ms)when publishing a message
import amqplib from "amqplib"
//1.连接MQ
const connection = await amqplib.connect("amqp://localhost:5672")
//2.创建一个通道
const channel = await connection.createChannel()
//3.创建交换机
/**
* @param {string} exchange 交换机名称 随便写
* @param {string} type 交换机类型 direct fanout topic headers x-delayed-message
* @param {options} options 可选配置项
*/
//这个方法就是说如果你创建过这个交换机就不会再创建了 如果没有创建过这个交换机就会创建
await channel.assertExchange("delayed-1", "x-delayed-message", {
arguments: {
"x-delayed-type": "direct", //目标交换机类型
},
})
//4.发送消息
/**
* @param {string} exchange 要发送到交换机的名称
* @param {string} routingKey 匹配路由的key
* @param {Buffer} buffer 要发送的消息
* @param {options} options 可选配置项
*/
channel.publish("delayed-1", "time", Buffer.from("延时消息"), {
headers: {
"x-delay": 10000, //延时 10秒
},
})
//断开连接
await channel.close()
await connection.close()
process.exit(0)
consumer
import amqplib from "amqplib"
//1.连接MQ
const connection = await amqplib.connect("amqp://localhost:5672")
//2.创建一个通道
const channel = await connection.createChannel()
//3.创建交换机
await channel.assertExchange("delayed-1", "x-delayed-message", {
arguments: {
"x-delayed-type": "direct", //目标交换机类型
},
})
//4.创建一个队列
const { queue } = await channel.assertQueue("queue-1")
//5.交换机跟队列要绑定
/**
* @param {string} queue 队列名称
* @param {string} exchange 交换机名称
* @param {string} routingKey 匹配路由的key
*/
channel.bindQueue(queue, "delayed-1", "time")
//6.消费消息
channel.consume(
queue,
(msg) => {
console.log(msg.content.toString())
},
{
noAck: true,
}
)
Effect demonstration

Nodejs Chapter 78 (Kafka)

What is Kafka?
The main design goal of Kafka is to provide a durable, high-throughput, fault-tolerant messaging system. It allows you to send and receive streaming data in a publish-subscribe manner and can handle large volumes of messages while maintaining low latency. Kafka's design also emphasizes distributed features, allowing it to run in large-scale clusters and handle large amounts of data and highly concurrent requests.
kafka architecture

- Producer: Producer, the producer of messages, is the entrance to messages
- Broker: Broker is an instance of kafka. Each server has one or more instances of kafka. A simple understanding is a kafka server. Kafka cluster means cluster.
- Topic: The topic of the message can be understood as a message queue, and Kafka data is stored in the topic. Multiple topics can be created on each broker.
- Partition: Topic partition. Each topic can have multiple partitions. The function of partition is to load and improve Kafka’s throughput. The data of the same 5. topic in different partitions is not repeated, and the partition is represented by folders one by one.
- Message: The body of each message sent.
- Consumer: The consumer, the consumer of the message, is the outlet of the message.
- Consumer Group: We can combine multiple consumer groups into one consumer group. In kafka's design, data in the same partition can only be consumed by one consumer in the consumer group. Consumers in the same consumer group can consume data from different partitions of the same topic. This is also to improve Kafka's throughput!
- Zookeeper: Kafka cluster relies on zookeeper to save the meta-information of the cluster to ensure the availability of the system.
Install Kafka
Install JDK because Kafka is written in java
java official website www.oracle.com/java/techno…

After the new version is installed successfully, you don’t need to configure the environment variables. The old version needs to be configured manually, just like the rabbitMQ chapter.
Note that you need to configure JAVA_HOME in the environment variable because zookeeper needs to read this environment variable. This is necessary.

Test whether the installation is successful
java --version

Install ZooKeeper
Because Kafka also uses ZooKeeper
ZooKeeper official website zookeeper.apache.org/releases.ht…

- Unzip apache-zookeeper-3.9.2-bin.tar.gz to your favorite directory and rename it
zookeeper - Open zookeeper\conf and rename
zoo_sample.cfgtozoo.cfg - Open
zoo.cfgand modify dataDir to./zookeeper/data - Configure
D: Applause\zoookeeper\bin (example)into the environment variable - Start, open cmd and execute
zkServer(do not close after startup is complete)

Install Kafka
Kafka official website kafka.apache.org/

- Unzip the downloaded file into a directory of your choice
- Rename the kafka folder to a shorter name, otherwise an error will be reported when executing commands later (because cmd cannot support very long commands)
- Open the kafka/config/server.properties file and modify log.dirs to
log.dirs=./logs - Start kafka and execute the following command in the kafka root directory
.\bin\windows\kafka-server-start.bat .\config\server.properties

Nodejs writes basic use cases to test kafka
Install dependencies kafkajs official website kafka.js.org/docs/gettin…
npm i kafkajs
Producer (i.e. sender)
// 导入所需的模块
import { Kafka } from "kafkajs"
// 创建一个 Kafka 实例,配置客户端ID和代理服务器地址(broker)
const kafka = new Kafka({
clientId: "xiaoMan", // 客户端ID,用于在 Kafka 中标识此客户端
brokers: ["localhost:9092"], // 代理服务器地址(broker),这里使用本地地址和默认端口
})
// 创建一个生产者实例
const producer = await kafka.producer()
// 连接到 Kafka 代理服务器
await producer.connect()
// 发送消息到指定主题
await producer.send({
topic: "task-1", // 指定要发送消息的主题
messages: [
{ value: "这是一条测试数据" }, // 要发送的消息内容
],
})
// 断开与 Kafka 代理服务器的连接
await producer.disconnect()
Consumer (that is, the party receiving the message)
// 导入所需的模块
import { Kafka } from "kafkajs"
// 创建一个 Kafka 实例,配置客户端ID和代理服务器地址(broker)
const kafka = new Kafka({
clientId: "xiaoMan", // 客户端ID,用于在 Kafka 中标识此客户端
brokers: ["localhost:9092"], // 代理服务器地址(broker),这里使用本地地址和默认端口
})
// 创建一个消费者实例,指定消费者组ID
const consumer = await kafka.consumer({ groupId: "my-group" })
// 连接到 Kafka 代理服务器
await consumer.connect()
// 订阅指定主题的消息,从头开始消费
await consumer.subscribe({ topic: "task-1", fromBeginning: true })
// 启动消费者并处理每条消息
await consumer.run({
eachMessage: async ({ topic, partition, message }) => {
console.log({
value: message.value.toString(),
})
},
})
Test case

Nodejs Chapter 79 (Kafka Advanced)

Kafka pre-knowledge has been discussed in the previous chapter and will not be repeated juejin.cn/post/737845…
kafka advanced
1. server.properties configuration file
server.properties is the configuration file of the Kafka server. It is used to configure all aspects of the Kafka service, including network settings, log storage, message retention policy, and security authentication.
#broker的全局唯一编号,不能重复
broker.id=0
#端口号
port=9092
#处理网络请求的线程数量
#接收线程会将接收到的消息放到内存中,然后再从内存中写入磁盘。
num.network.threads=3
#用来处理磁盘IO的线程数量
#消息从内存中写入磁盘是时候使用的线程数量。
num.io.threads=8
#发送套接字的缓冲区大小
socket.send.buffer.bytes=102400
#接受套接字的缓冲区大小
socket.receive.buffer.bytes=102400
#请求套接字的缓冲区大小
socket.request.max.bytes=104857600
#kafka运行日志存放的路径
log.dirs=./logs
#topic在当前broker上的分区个数
num.partitions=1
#用来恢复和清理data下数据的线程数量
num.recovery.threads.per.data.dir=1
#每个topic的分区数
offsets.topic.replication.factor=1
#每个topic的副本数
transaction.state.log.replication.factor=1
#每个topic的最小副本数
transaction.state.log.min.isr=1
#日志保留时间,单位小时 168就是7天
log.retention.hours=168
#定期检查日志是否过期的间隔,单位毫秒
log.retention.check.interval.ms=300000
#日志清理器是否启用
log.cleaner.enable=true
#zookeeper地址
zookeeper.connect=localhost:2181
#zookeeper连接超时时间
zookeeper.connection.timeout.ms=18000
#zookeeper会话超时时间
group.initial.rebalance.delay.ms=0
2.producer.properties configuration file
producer.properties is the configuration file of the Kafka producer client, used to configure the behavior and properties of the Kafka producer. You can use this configuration file when you use the Kafka producer API to send messages to the Kafka cluster.
#配置生产者的broker列表 可以配置多个,以逗号隔开 也就是做集群的
#来获取每一个topic的分片数等元数据信息。
bootstrap.servers=localhost:9092
# 配置数据压缩方式 有none,gzip,snappy,lz4,zstd
compression.type=none
#客户端等待请求的响应的最长时间 超时时间
#request.timeout.ms=
#定期发送消息的时间间隔,一般配合batch.size使用,例如设置了50ms,那么每50ms就会发送一次消息合集
#linger.ms=
#每次发送给Kafka服务器请求消息的最大大小
#max.request.size=
#批量发送消息比如说设置了值16KB,那么消息内容凑够16KB就会被发送出去,否则就不会发送,这样可以避免单条消息太大导致的发送失败
#batch.size=
#约束producer缓存池的大小,默认是32MB,可以根据实际情况调整
#buffer.memory=
3.consumer.properties configuration file
Properties used to configure Kafka consumers. It contains a series of parameters and values used to define consumer behavior
#定义Kafka的Broker列表 可以配置多个,以逗号隔开 也就是做集群的
bootstrap.servers=localhost:9092
#定义消费者组的ID
group.id=test-consumer-group
#用于指定当消费者加入一个消费者组但没有可用的消费位移时的行为
#有三种选项 earliest/latest/none
#earliest:表示消费者将从最早的可用消费位移开始消费。消费者将从主题的最早消息开始消费,即使这些消息已经过期。
#latest:表示消费者将从最新的可用消费位移开始消费。消费者将从主题的最新消息开始消费,即跳过已经过期的消息。
#none:表示如果没有可用的消费位移,消费者将抛出异常。这样可以确保消费者只消费已经提交的消费位移。
#auto.offset.reset=
#心跳间隔用于保持消费者活跃状态
#session.timeout.ms
#指定消费者一次性获取最大的消息数量,如果为0表示不限制
#fetch.max.bytes=1048576
#指定消费者一次性获取的最大等待时间,如果为0表示不限制
#fetch.max.wait.ms=500
Message mode
Kafka also supports publishing and subscribing to send messages. Let’s write a case.
Official documentation kafka.js.org/docs/gettin…
1. Compression
Introduce CompressionTypes Select compression mode GIZP LZ4 zSTD
import { Kafka, CompressionTypes } from "kafkajs"
await producer.send({
topic: "xiaoman",
compression: CompressionTypes.GZIP,
messages: [
{
value: "测试数据1",
headers: {
name: Buffer.from("小满"),
},
},
{ value: Buffer.from("测试数据2") },
],
})
2. Header
Allows the use of headers to pass object metadata. Put the data that needs to be passed in headers and the data will be sent together.
await producer.send({
topic: "xiaoman",
messages: [
{
value: "测试数据1",
headers: {
name: Buffer.from("小满"),
},
},
{ value: Buffer.from("测试数据2") },
],
})
Consumers obtain headers metadata
await consumer.run({
eachMessage: async ({ topic, partition, message }) => {
console.log({
topic,
partition,
value: message.value.toString(),
headers: message.headers?.name?.toString(),
})
},
})
3. Multi-theme distribution
Change the sending method of send to sendBatch and add topicMessages, which is an array.
await producer.sendBatch({
topicMessages: [
{
topic: "xiaoman",
messages: [{ value: Buffer.from("测试数据1") }],
},
{
topic: "xiaoman2",
messages: [{ value: Buffer.from("测试数据2") }],
},
],
})
When consuming multiple messages, you can freely choose the mode according to the business.
- Process item by item
- Batch processing (batch processing can reduce network overhead)
await consumer.subscribe({ topic: "xiaoman", fromBeginning: true })
await consumer.subscribe({ topic: "xiaoman2", fromBeginning: true })
//逐条处理
await consumer.run({
eachMessage: async ({ topic, partition, message }) => {
console.log({
topic,
partition,
value: message.value.toString(),
headers: message.headers?.name?.toString(),
})
},
})
//批量处理
await consumer.run({
eachBatch: async ({ batch }) => {
batch.messages.forEach((message) => {
console.log("Received message", message.value.toString())
})
},
})
Case Demonstration

Nodejs Chapter 80 (Kafka Advanced)

Kafka pre-requisite knowledge has been discussed in the previous chapters and will not be repeated juejin.cn/post/737845…
Kafka cluster operations
1. Create multiple kafka services
Copy the complete directory of kafka and rename it to kafka2

Modify the configuration file kafka2/config/server.properties this file
broker.id=1 //唯一broker
port=9093 //切换端口
listeners=PLAINTEXT://:9093 //切换监听源
Start zooKeeper and kafka and kafka2
.\bin\windows\kafka-server-start.bat .\config\server.properties

2. Client management
View cluster information and client objects
import { Kafka, CompressionTypes } from "kafkajs"
const kafka = new Kafka({
clientId: "my-app", //客户端标识
brokers: ["localhost:9092", "localhost:9093"], //kafka集群
})
const admin = kafka.admin() //创建admin对象
await admin.connect() //连接kafka
const cluster = await admin.describeCluster() //获取集群信息
Return value: You can view information about the connection to the cluster, such as port ID, etc.
{
brokers: [
{ nodeId: 0, host: '26.26.26.1', port: 9092 },
{ nodeId: 1, host: '26.26.26.1', port: 9093 }
],
controller: 0,
clusterId: 'XHa77me4TZWO8cfWSTHoaQ'
}
Creating the topic createTopics will resolve whether the true topic was successfully created or whether false already exists. If an error occurs, this method will throw an exception
Delete topic admin.deleteTopics Pass in the deleted topic
View Topic List listTopics lists the names of all existing topics and returns a string array. If an error occurs, this method will throw an exception.
//创建主题
await admin.createTopics({
topics: [
{ topic: "xiaoman", numPartitions: 1, replicationFactor: 1 },
{ topic: "xiaoman2", numPartitions: 1, replicationFactor: 1 },
],
})
//删除主题
await admin.deleteTopics({ topics: ["xiaoman", "xiaoman2"] })
//查看主题
await admin.listTopics().then((topics) => {
console.log("topics", topics)
})
3. Affairs
KafkaJS provides support for Kafka transactions, which can be used to perform operations with transactional characteristics. Kafka transactions are used to ensure that a set of related messages is either Successful submission of all, Or we'll roll back., thereby maintaining data consistency
import { Kafka, CompressionTypes } from "kafkajs"
const kafka = new Kafka({
clientId: "my-app", //客户端标识
brokers: ["localhost:9092", "localhost:9093"], //kafka集群
})
//生产者
const producer = kafka.producer({
transactionalId: "填写事务ID",
maxInFlightRequests: 1, //最大同时发送请求数
idempotent: true, //是否开启幂等提交
})
//连接服务器
await producer.connect()
const transaction = await producer.transaction()
try {
await transaction.send({
topic: "xiaoman",
messages: [{ value: "100元" }],
})
await transaction.commit() // 事务提交
} catch (e) {
console.log(e)
await transaction.abort() // 事务提交失败,回滚
}
await admin.disconnect()
Nodejs Chapter 81 (Nacos Registration Center)

What is Nacos?
Official website nacos.io/zh-cn/docs/…
Nacos is an open source project of Alibaba. It can help you discover, configure and manage microservices. Nacos provides an easy-to-use feature set to help you quickly implement dynamic service discovery, service configuration, service metadata and traffic management solutions.
- Service registration: Applications can register their own service instances to the Nacos registration center, including the service's unique identifier, network address, metadata, etc. By registering, service providers can inform Nacos of their existence and availability.
- Service discovery: Applications can query the Nacos registry to discover available services. Service consumers can obtain the service provider's information, such as IP address and port, by querying the registration center in order to establish communication with it.
- Service health check: The Nacos registration center can periodically check the health status of registered service instances. It can determine whether the service is available by sending a heartbeat check request to the service instance and based on the response status.
- Load balancing: Through the registration center, service consumers can obtain multiple available service instances and use the load balancing algorithm to select one of them for request processing. This improves system availability and performance.
Dynamic Configuration Management: The Nacos registration center also provides dynamic configuration management functions. Applications can register configuration information into Nacos and can dynamically modify and refresh it at runtime. This avoids application restarts or redeployments to update the configuration.
Installation

1. After downloading, unzip it to the directory you like. Remember to change the name to something shorter, such as nacos
2. Modify the configuration file to connect to the database D:\Applaaction\nacos\conf\application.properties
//把注释打开默认是注释掉的 大概在42行左右
db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user.0=root
db.password.0=123456

3. Import nacos database file and register the database
CREATE DATABASE `nacos`
DEFAULT CHARACTER SET = 'utf8mb4';

Right-click to import the sql file, select the mysql-schema.sql file under the cong directory, and then import

4. Write startup command
Just put it on the desktop
cd D:\Applaaction\nacos\bin
./startup.cmd -m standalone
5. Install java environment
Official website www.oracle.com/java/techno…

After the new version is installed successfully, you don’t need to configure the environment variables. The old version needs to be configured manually, just like the rabbitMQ chapter.
6. Start nacos
Double-click the startup script you just wrote. The bat file written in Section 4

7. Access nacos client

Code Case Nodejs
npm install nacos
Server registration + health check
Post.js simply creates a service port 8080
import http from "node:http"
http
.createServer((req, res) => {
res.setHeader("Content-Type", "application/json")
res.end(JSON.stringify({ msg: "8080Server" }))
})
.listen(8080, () => {
console.log("8080Server")
})
User.js simply starts a service with port 8081
import http from "node:http"
http
.createServer((req, res) => {
res.setHeader("Content-Type", "application/json")
res.end(JSON.stringify({ msg: "8081Server" }))
})
.listen(8081, () => {
console.log("8081Server")
})
register.js
import Nacos from "nacos"
const client = new Nacos.NacosNamingClient({
serverList: ["127.0.0.1:8848"], // 服务地址
namespace: "public", // 命名空间
logger: console, // 用于打印日志
})
await client.ready() // 等待注册中心连接成功
const postServerName = "postServices"
client.registerInstance(postServerName, {
ip: "127.0.0.1", // 服务实例IP
port: 8080, // 服务实例端口
weight: 1, // 服务实例权重
enable: true, // 是否健康检查
healthy: true, // 是否健康
metadata: {
"nacos.healthcheck.type": "HTTP", // 健康检查方式
"nacos.healthcheck.url": "/health", // 健康检查地址
"nacos.healthcheck.interval": 5, // 健康检查间隔时间
"nacos.healthcheck.timeout": 3, // 健康检查超时时间
},
})
const userServerName = "userServices"
client.registerInstance(userServerName, {
ip: "127.0.0.1", // 服务实例IP
port: 8081, // 服务实例端口
weight: 1, // 服务实例权重
enable: true, // 是否健康检查
healthy: true, // 是否健康
metadata: {
"nacos.healthcheck.type": "HTTP", // 健康检查方式
"nacos.healthcheck.url": "/health", // 健康检查地址
"nacos.healthcheck.interval": 5, // 健康检查间隔时间
"nacos.healthcheck.timeout": 3, // 健康检查超时时间
},
})

Nodejs Chapter 82 (Nacos dynamic configuration)

What is dynamic configuration?
In Nacos, dynamic configuration means that the configuration information of an application can be dynamically modified at runtime without the need to restart or redeploy the application. Through Nacos' dynamic configuration feature, developers can store the application's configuration information in the Nacos server and modify and update it when needed. In this way, even if the application is already running, the configuration can be updated by modifying the configuration information in Nacos, thus avoiding the trouble of redeployment.
Give a chestnut

For example, if our service is deployed to three servers and needs to be connected to the database, if the account password or other configuration items of the database change, we need to modify the configuration items and then restart the service. It is too troublesome to restart the service three times, so there is dynamic configuration. These configuration items are stored in nacos, and the configuration information of nacos is modified to dynamically update the configuration items.

Case Demonstration
Add, delete, modify and check configuration items visual version

- Data ID is a key
- Group grouping
- Configuration format is the data format you want to store.
- Configuration content and stored data

Add, delete, modify and check configuration items code version
- New configuration item for publishSingle
- remove Delete configuration items
- getConfig reads configuration items
- subscribe to monitor changes in configuration items
import express from "express"
import { NacosConfigClient } from "nacos"
const app = express()
const client = new NacosConfigClient({
serverAddr: "127.0.0.1:8848",
})
//新增一个配置项
//const content = await client.publishSingle('config', 'DEFAULT_GROUP', '{"host":"127.0.0.1","port":8848}')
//删除一个配置项
//await client.remove('config', 'DEFAULT_GROUP')
//查询一个配置项
//const config = await client.getConfig('config', 'DEFAULT_GROUP')
//监听配置变化
// client.subscribe({ dataId: 'config', group: 'DEFAULT_GROUP', },
// content => {
// console.log(content)
// }
// )
app.get("/", async (req, res) => {
res.json({
code: 200,
content: JSON.parse(config),
})
})
app.listen(3000, () => {
console.log("3000Server")
})
Nodejs Chapter 83 (ElasticSearch full text search)
What is ElasticSearch?
ElasticSearch is an open source, distributed search and analysis engine that is particularly good at processing large-scale log and text data. It is built on Apache Lucene and provides powerful full-text search capabilities and real-time data analysis capabilities. ElasticSearch is commonly used for real-time search and analysis of log and event data, as well as full-text retrieval of large text data.

Scene
- Application Log Analysis: Analyze application logs in real time to quickly discover and solve problems.
- Website Search: Provides fast full-text search function for websites to improve user experience
- Map Service: Provide location-based search and navigation services
Installation
1. Install elastic
Download address www.elastic.co/cn/download…

- Select the operating system you have and download it
- Unzip it to your favorite directory
If you want to use your own java version to configure the JAVA_HOME environment variable, you can also use the JDK that comes with Elastic. The current version is 21.0.2
- Start and run the
elasticsearchfile under the bin directory - Modify the elastic password and execute
elasticsearch-reset-password -u elastic -iunder the bin directory and then enter the password, for example 123456 - Close https and open
elasticSearch/config/elasticsearch.ymland change it to false

Just visit http://localhost:9200. The default port is 9200.

- The account number is elastic and the password is the fourth password you modified. Return the following information to succeed.

2. Install kibana
Kibana is an open source analytics and visualization platform designed to work with Elasticsearch. You use Kibana to search, view, and interact with data stored in Elasticsearch indexes.
Download address www.elastic.co/cn/download…
Just select the corresponding operating system

Kibana is developed based on the Nodejs environment, and Nodejs needs to be installed. If you have already installed it, ignore it.
- After downloading, unzip it to your favorite directory (just wait if the decompression is slow)
- After decompression is complete, run the
kibana/bin/kibana.batfile. - After opening, visit
http://localhost:5601/

Add test data

Access test data

Connect to Node.js
Install dependency packages
npm install @elastic/elasticsearch
Implementation of additions, deletions and modifications
core concepts
- Index is similar to the database concept in relational database. It is a collection containing documents. Each index has a name, which is used as an identifier when performing operations such as searching, updating, and deleting. In fact, it is similar to
databasein the database. - Document (document) Document is the basic information unit in Elasticsearch, similar to the row (row) in a relational database. Documents are stored in JSON format. Each document contains one or more fields, which are in the form of key-value pairs.
import { Client } from "@elastic/elasticsearch"
const client = new Client({
node: "http://localhost:9200",
auth: {
username: "elastic",
password: "123456",
},
})
//创建索引 + 数据
const user = await client.index({
index: "user-data",
document: {
user: 1,
age: 18,
name: "jack",
},
})
//查询数据
const response = await client.get({
index: "user-data",
id: user._id, //id可以指定也可以让elasticsearch自动生成
})
//搜索
const result = await client.search({
index: "user-data", //指定索引
query: {
//查询条件
match: {
name: "jack", //模糊查询
},
},
size: 1, //指定返回条数
})
console.log(result.hits.hits) //打印搜索结果
//删除
await client.delete({
index: "user-data",
id: user._id,
})
Visual usage
# 创建索引
PUT /task-index
# 添加文档到索引
POST /task-index/_doc
{
"id": "1",
"title": "不是哥们",
"description": "杰哥不要啊杰哥??????????、啊"
}
# 搜索信息 q就是query的简写
GET /task-index/_search?q="杰哥"

Nodejs Chapter 84 (ElasticSearch search)

The basic usage of ElasticSearch has been introduced in the previous chapter. I won’t elaborate too much here.
Simulate fake data
- Install the library
@faker-js/faker, a library that simulates fake data and is very easy to use and supports Chinese. - Use Chinese locale: [zh_CN], just set it
- Generate name, email, mobile phone number, ID, age, gender
- After the generation is completed, use fs to write the
data.jsonfile
import { Faker, zh_CN } from "@faker-js/faker"
const faker = new Faker({
locale: [zh_CN],
})
const generate = (total = 100) => {
let arr = []
for (let i = 0; i < total; i++) {
arr.push({
name: faker.person.fullName(),
email: faker.internet.email(),
phone: faker.string.numeric({ length: 11 }),
id: faker.string.uuid(),
age: faker.number.int({ min: 18, max: 60 }),
isMale: faker.datatype.boolean(),
})
}
return arr
}
fs.writeFileSync("./data.json", JSON.stringify(generate(), null, 2))
fake data
[{
"name": "隐强",
"email": "k7nggq88@126.com",
"phone": "79533230542",
"id": "945e80bb-9ece-428b-925c-1ed01e26d660",
"age": 44,
"isMale": true
},
......]
Node.js integrates ElasticSearch
- fs reads the file just written
- Install the ElasticSearch package
@elastic/elasticsearc - You can use apiKey to connect to elastic, or you can use the account and password mode. Here, the account and password are used, and in production, apiKey is used.
- Check whether this index
Error if created repeatedlyhas been created before - If this index has not been created, create it and build the mapping table, which is the field
properties - Batch insert data encapsulates a function
bulkInsert - Implement the inserted function
bulkInsert - Search
//1.第一步
const data = fs.readFileSync("./data.json", "utf-8")
const arr = JSON.parse(data)
//2.第二步
import { Client } from "@elastic/elasticsearch"
//3.第三步
const client = new Client({
node: "http://localhost:9200",
auth: {
username: "elastic",
password: "123456",
},
})
//4.第四步
const exists = await client.indices.exists({ index: "users" })
//5.第五步
if (!exists) {
await client.indices.create({
index: "users",
mappings: {
properties: {
name: { type: "text", fields: { keyword: { type: "keyword" } } },
email: { type: "text" },
phone: { type: "text" },
id: { type: "text" },
age: { type: "integer" },
isMale: { type: "boolean" },
},
},
})
//6.第六步
await bulkInsert(arr)
}
//7.第七步
const bulkInsert = async (data) => {
const operations = []
data.forEach((item) => {
operations.push({
index: {
_index: "users",
_id: item.id,
},
})
operations.push(item)
})
//批量插入
await client.bulk({ refresh: true, operations })
}
//8.搜索
const response = await client.search({
index: "users",
query: {
match_all: {},
},
size: 100,
})
console.log(response.hits.hits)
Search details
Based on the above code + explanation, we have a basic understanding of its working principle. The most powerful thing about ElasticSearch is its search ability. It can be searched in various combinations. Let’s demonstrate it separately.
1. All queries
match_all is all query Note that the default returns only ten. You can configure the number of bars you want to return.
const response = await client.search({
index: "users",
query: {
match_all: {}, //空对象即可
},
size: 100, //返回100条
})

2. Fuzzy query
Fuzzy query will perform word segmentation and match all keywords
Use match to perform fuzzy query. Enter the field to be matched, such as name, followed by value, such as Invisible. It will match all the content containing the two words Invisible in the data. My data contains Invisible Chiang Keung Kai Keung., so three items are returned.
const response = await client.search({
index: "users",
query: {
match: {
name: "隐强",
},
},
size: 100,
})
console.log(response.hits.hits)

3. Precise query
If you need to support precise query, you need to set
name: { type: 'text', fields: { keyword: { type: 'keyword', } } },because the text type will support word segmentation by default and is designed for full-text search. However, if you want to support both full-text matching + precise matching, you need to set the type keyword
Note that match is not used here, and is changed to term [field.keyword] = [value] query
const response = await client.search({
index: "users",
query: {
term: {
"name.keyword": "隐强",
},
},
size: 100,
})
console.log(response.hits.hits)

4. Combined query
- Must must match the condition. It matches here (implicitly strong)
- Filter condition filtering matches age (people aged 20-60)
- must_not must not match (here it means that the returned value cannot contain people with Chinese characters)
- should optional condition (implicitly matched here)
const response = await client.search({
index: "users",
query: {
bool: {
must: {
match: {
name: "隐强",
},
},
filter: {
range: {
age: {
gte: 20,
lte: 60,
},
},
},
must_not: {
match: {
name: "国",
},
},
should: {
match: {
name: "隐强",
},
},
},
},
size: 100,
})
console.log(response.hits.hits)

5. Aggregation query
Aggregation queries are used in Elasticsearch to count, summarize, and analyze data. It can provide in-depth insights and insights about the data set.
Case: Count the number of occurrences of each age. Note that aggs is no longer query.
const response = await client.search({
index: "users",
aggs: {
age: {
terms: {
field: "age",
},
},
},
size: 100,
})
console.log(response.aggregations.age.buckets)
return value
key: Represents the aggregated field value, which here looks like age.
doc_count: Indicates the number of documents with this age.
[
{ "key": 32, "doc_count": 6 }, //表示年龄32 出现6次
{ "key": 23, "doc_count": 4 }, //表示年龄23 出现4次
{ "key": 28, "doc_count": 4 }, //.......
{ "key": 29, "doc_count": 4 },
{ "key": 49, "doc_count": 4 },
{ "key": 51, "doc_count": 4 },
{ "key": 60, "doc_count": 4 },
{ "key": 21, "doc_count": 3 },
{ "key": 22, "doc_count": 3 },
{ "key": 24, "doc_count": 3 }
]
Nodejs Chapter 85 (Cluster)
What is a cluster?
Node.js Cluster is a technology used to create multiple Node.js processes on multi-core systems to fully utilize all CPU cores of the system, thereby improving application performance and availability. Node.js itself is single-threaded, and the cluster module provides a way to process workloads in parallel by using multiple processes.
Basic concepts
Single-threaded limitation: Node.js is based on a single-threaded event-driven model and can only use one CPU core by default.
Multi-process architecture: With the cluster module, multiple Node.js processes (called worker processes) can be created, each of which can handle part of the traffic, thus utilizing multiple CPU cores.

Case Demonstration
Node.js provides the built-in cluster module to create and manage clusters. Using this module, one can easily create multiple worker processes and share the same server port
index.js
import cluster from "node:cluster"
import http from "node:http"
import os from "node:os"
const cpus = os.cpus().length
// 主进程
if (cluster.isPrimary) {
for (let i = 0; i < cpus; i++) {
cluster.fork() // 创建子进程
}
}
// 子进程
else {
http
.createServer((req, res) => {
res.writeHead(200)
res.end("cluster is running")
})
.listen(3000, () => {
console.log("http://127.0.0.1:3000")
})
}
Use ps node to query the process

Comparison between cluster operation and non-cluster operation
Write a non-cluster service, index2.js runs non-cluster
import http from "node:http"
http
.createServer((req, res) => {
res.writeHead(200)
res.end("cluster is running")
})
.listen(6000, () => {
console.log("http://127.0.0.1:6000")
})
Install testing tools
npm install -g loadtest
execute command
loadtest http://localhost:3000 -n 50000 -c 100
loadtest http://localhost:6000 -n 50000 -c 100
-c indicates the number of concurrent users or concurrent connections. In this case, -c 100 means that when performing load testing, simulate 100 concurrent users or establish 100 concurrent connections at the same time
-n indicates the total number of requests or the total number of requests. In this case, -n 50000 means that when performing a load test, a total of 50,000 requests will be sent to the target website

We can see that the average latency of the cluster is 161ms and that of the non-cluster is 234.7ms. Based on these tests, we can see that the cluster does not bring much improvement to the performance of the application, but the security of the interface still ensures that there are almost no failed requests.
Nodejs Chapter 86 (Deploying pm2)
How to deploy Node.js?
If you want to deploy a Nodejs project, the first point is definitely a server, and the second point is a deployment tool. Here we use pm2.

PM2
PM2 is a very popular Node.js process management tool for running and monitoring Node.js applications in production environments. It provides a variety of functions to help developers better manage and optimize their applications. There are actually many things pm2 can do, such as monitoring file changes and automatically restarting, unified management of multiple processes, built-in load balancing, logging system, etc.
Process Management: PM2 makes it easy to start, stop, restart, and delete Node.js application processes. It supports launching multiple processes to take advantage of multi-core CPUs, improving application performance and stability.
Load Balancing: Through cluster mode, PM2 can create multiple application instances and automatically perform load balancing to ensure that applications can still run stably under high concurrency conditions.
Automatic restart: When the application crashes or an error occurs, PM2 can automatically restart the application to ensure high availability of the service.
Log Management: PM2 provides comprehensive log management functions that can easily view, merge and analyze application log information.
Monitoring and Performance Analysis: PM2 has built-in monitoring capabilities that allow you to view application performance metrics (such as CPU and memory usage) in real time. Additionally, PM2 integrates with Keymetrics, a performance monitoring and management platform specifically for Node.js applications.
Configuration file support: PM2 supports configuration through JSON files or JavaScript files, making it easy to manage multiple applications and environment configurations.
Hot Reload: PM2 can reload application code without stopping the service, reducing downtime.
Container support: PM2 can be well integrated with container technologies such as Docker to facilitate the management of Node.js applications in a containerized environment.
Basic usage
1. Installation
npm install pm2 -g
2.Basic use
Create a service at will. Of course, express, koa, nestjs can also be used. Here is just an example of http code that was lazily written.
import http from "node:http"
http
.createServer((req, res) => {
res.writeHead(200)
res.end("cluster is running")
})
.listen(6000, () => {
console.log("http://127.0.0.1:6000")
})
1. You can start one service or multiple services.
pm2 start app.js xx.js bb.js ......
2. View the currently running node process
pm2 list

3. Stop a node process
pm2 stop [process_id]

4. Restart the service
pm2 restart [process_id]
5. Delete service
pm2 delete [process_id]
6. Start automatically after booting
linux
- First run a script such as
pm2 start app.js - Save process information
pm2 save - Generate startup script
pm2 startup - Boot auto-start command
pm2 startup systemd - Save the self-start command
pm2 save - Delete automatic startup
pm2 unstartup systemd - Save, delete and start
pm2 save
windows
- Install windows automatic startup package
npm install pm2-windows-startup -g - Install the self-starting script
pm2-startup install - Start service
pm2 start xxxx - Save the self-starting service
pm2 save - Delete automatic startup
pm2-startup uninstall
3. Log
Various log feedback can be collected to debug issues
pm2 log

4. Monitoring panel
All processes managed by PM2 can be monitored in real time. This monitoring panel provides a wealth of real-time data, including CPU usage, memory usage, restart times, log output and other information
Real-time Monitoring: Monitor application performance in real-time in development and production environments, and detect and handle exceptions in a timely manner.
Debug and Diagnose: View log output to help debug and diagnose problems.
Resource Management: Monitor resource usage and optimize application performance and resource allocation.
pm2 monit

5. Load balancing
In the previous chapter, we introduced the cluster capabilities. Of course, pm2 internally encapsulates the cluster capabilities to make our applications more powerful.
pm2 start index.js -i [max | number]
You can specify the number of warp threads, or you can set max to directly set the highest value.

6. Configuration file
Call the following command to generate the configuration file ecosystem.config.js in the project or create it manually
pm2 init simple
ecosystem.config.js
apps: [
{
name: "my-app",
script: "./app.js",
instances: 4,
exec_mode: "cluster",
watch: true,
max_memory_restart: "200M",
env: { NODE_ENV: "development", PORT: 3000 },
env_production: { NODE_ENV: "production", PORT: 8080 },
},
]
apps: An array containing application configuration objects, each object represents an application.
name: Application name, used for identification in PM2.
script: The path of the script file to be started.
instances: Number of instances, either a specific number or max, to utilize all available CPU cores.
exec_mode: Execution mode, common values are fork (default) and cluster.
watch: Enable file monitoring. If the file changes, the application will automatically restart.
max_memory_restart: Automatically restart the application when memory usage exceeds the specified value.
env: Common environment variable configuration.
env_production: Production environment variable configuration, effective when started using the pm2 start ecosystem.config.js --env production command.
enable profile
pm2 start ecosystem.config.json #这样就可以了 不用在单独指定js文件了
The deployment server operation is also the same
Conclusion
This is the end of the Nodejs course. New APIs will be added in the future. Thank you all for your support along the way. In addition, this set of Nodejs tutorials has accompanying video tutorials.
Beep-Bee-Bee-Bee-Bee-Bee.
I wanted to buy sweet-scented osmanthus and drink it with me, but it didn’t look the same. Young man wandering around
