Moonlit Torii

Node.js

Node.js articles combined in their original column publication order.

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

  1. nodejs is not a JavaScript application, nor is it a programming language, because the programming language uses JavaScript, and Nodejs is the runtime of JavaScript.

Figure 1 for Node.js

  1. 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.
  2. 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 libuv event loop library.
  3. 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/
  4. 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 cluster provided by nodejs. (CPU-intensive refers to image processing or audio processing that requires a large number of data structures + algorithms)

nodeJs rough architecture diagram

Figure 2 for Node.js

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.

View original text


Nodejs Chapter 2 (Installation)

Install nodejs

Visit official website

  1. en nodejs.org/en
  2. cn www.nodejs.com.cn/

Figure 3 for Node.js

LTS long-term support version

Current early adopter version

Figure 4 for Node.js

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

Figure 5 for Node.js

windows msi

Figure 6 for Node.js

You can also download the compressed package yourself and configure environment variables

Check if the installation is successful

Figure 7 for Node.js

View original text


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.

www.npmjs.com/

  • 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

  1. npm init: Initialize a new npm project and create a package.json file.
  2. npm install: Install a package or a group of packages and store a node_modules in the current directory.
  3. npm install <package-name>: Install the specified package.
  4. npm install <package-name> --save: Install the specified package and add it to the dependency list in the package.json file.
  5. npm install <package-name> --save-dev: Install the specified package and add it to the development dependency list in the package.json file.
  6. npm install -g <package-name>: Install the specified package globally.
  7. npm update <package-name>: Update the specified package.
  8. npm uninstall <package-name>: Uninstall the specified package.
  9. npm run <script-name>: Execute the script command defined in the package.json file.
  10. npm search <keyword>: Search the npm library for packages containing the specified keyword.
  11. npm info <package-name>: View detailed information of the specified package.
  12. npm list: List all packages installed in the current project.
  13. npm outdated: List the packages that need to be updated in the current project.
  14. npm audit: Check dependencies in the current project for security vulnerabilities.
  15. npm publish: Publish the self-developed package to the npm library.
  16. npm login: Log in to your npm account.
  17. npm logout: Log out of the current npm account.
  18. npm link: Link the local module to the global node_modules directory
  19. npm config list is 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)
  20. npm get registry is 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.
  21. npm set registry npm 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

  1. name: Project name, must be a unique string, usually a combination of lowercase letters and hyphens.
  2. version: Project version number, usually using semantic version number specification.
  3. description: Project description.
  4. main: The path of the main entry file of the project, usually a JavaScript file.
  5. keywords: Keyword list of the project to facilitate others to search and discover the project.
  6. author: Information about the project author, including name, email, website, etc.
  7. 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.).
  8. dependencies: A list of packages that the project depends on. These packages will be automatically installed when the project is run.
  9. 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.
  10. peerDependencies: The peer dependency of the project, that is, the modules required by the project are dependent on other modules.
  11. scripts: Defines some script commands, such as starting projects, running tests, etc.
  12. repository: Information about the project code warehouse, including type, URL, etc.
  13. bugs: The project’s bug report address.
  14. homepage: The official website address or document address of the project.

Figure 8 for Node.js

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

View original text


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.

Figure 9 for Node.js

Flat?

Flatness is only the ideal state as follows

Figure 10 for Node.js

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

Figure 11 for Node.js

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

Figure 12 for Node.js

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.

sh
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.

Figure 13 for Node.js

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

Figure 14 for Node.js

View original text


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.

Figure 15 for Node.js

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

Figure 16 for Node.js

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! ! !

json
    "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…

Figure 17 for Node.js

View original text


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

  1. Avoid global installation: npx allows you to execute npm packages without requiring you to install it globally first.
  2. Always use the latest version: If you do not install the corresponding npm package locally, npx will download and use the latest version from the npm package repository.
  3. Execute any npm package: npx can not only execute the commands defined in the scripts part of package.json, but also execute any npm package.
  4. Execute GitHub gist: npx can 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…

Figure 18 for Node.js

For example, when creating a react project, it needs to be installed globally.

sh
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

bash
npm ls -g 查看全局安装的包

Figure 19 for Node.js

I have not installed vite globally.

Install vite for the current project

css
npm i vite -D

Figure 20 for Node.js

After the installation was completed, I found that I could not execute the vite command.

At this time you can use npx vite

Figure 21 for Node.js

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.

View original text


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

sh
npm adduser

First check if it is an npm source and then create an npm account.

Figure 22 for Node.js

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

Figure 23 for Node.js

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

Figure 24 for Node.js

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

Figure 25 for Node.js

View original text


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.org/zh-CN/

Verdaccio is a tool that can help us quickly build npm private servers

sh
npm install verdaccio -g

Very simple to use

verdaccio can be run directly

Figure 26 for Node.js

Then access the default port 4873

Figure 27 for Node.js

Just switch to simplified Chinese

Figure 28 for Node.js

Basic commands

sh
#创建账号
npm adduser --registry http://localhost:4873/
# 账号 密码 邮箱
sh
# 发布npm
npm publish --registry http://localhost:4873/
sh
#指定开启端口 默认 4873
verdaccio --listen 9999
sh
# 指定安装源
npm install --registry http://localhost:4873
sh
# 从本地仓库删除包
npm unpublish <package-name> --registry http://localhost:4873

Other configuration file items

verdaccio.org/zh-CN/docs/…

View original text


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

  1. Support the introduction of built-in modules such as http os fs child_process and other nodejs built-in modules
  2. Support the introduction of third-party modules express md5 koa, etc.
  3. Support the introduction of self-written modules ./ ../ etc.
  4. Support the introduction of addon C++ extension module .node file
js
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

js
module.exports = {
  hello: function () {
    console.log("Hello, world!")
  },
}

If you don’t want to export the object, export the value directly

js
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

js
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.

js
import data from './data.json' assert { type: "json" };
console.log(data);

Load the overall object of the module

js
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.

js
if (true) {
  import("./test.js").then()
}

module export

  • Exporting a default object default can only have one non-repeatable export default
js
export default {
  name: "test",
}
  • Export variables
js
export const a = 1

The difference between Cjs and ESM

  1. Cjs is based on synchronous loading at runtime, and esm is based on asynchronous loading at compile time.
  2. Cjs can modify the value, but the esm value cannot be modified (readable)
  3. Cjs cannot support tree shaking, but esm supports tree shaking.
  4. 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
js
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
js
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
js
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

js
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

js
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

js
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.

View original text


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

js
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

js
__dirname

It indicates the absolute path of the current module Contents

js
__filename

It represents the absolute path of the current module Documentation, including the file name and file extension

js
require module

The introduction of modules and module exports have been discussed in detail in the previous chapter.

js
process
  1. 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.
  2. process.env: This is an object containing the current environment variables. You can access and manipulate environment variables through process.env.
  3. process.cwd(): This method returns the path of the current working directory.
  4. process.on(event, listener): used to register event listeners. You can use process.on to listen for events such as exit, uncaughtException, etc., and execute the corresponding callback function when the event occurs.
  5. process.exit([code]): used to exit the current Node.js process. You can provide an optional exit code as a parameter.
  6. 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.

js
Buffer
  1. Create Buffer instance:
  • Buffer.alloc(size[, fill[, encoding]]): Creates a new Buffer instance of the specified size with initial content of zero. The fill parameter can be used to fill the buffer, and the encoding parameter specifies the character encoding for filling.
  • Buffer.from(array): Creates an instance of Buffer containing the given array.
  • Buffer.from(string[, encoding]): Creates an instance of Buffer containing the given string.
  1. Read and write data:
  • buffer[index]: Read or write specific bytes in the Buffer instance by index.
  • buffer.length: Get the byte length of the Buffer instance.
  • buffer.toString([encoding[, start[, end]]]): Convert Buffer instance to string.
  1. Convert data:
  • buffer.toJSON(): Convert Buffer instance to JSON object.
  • buffer.slice([start[, end]]): Returns a new Buffer instance containing part of the original Buffer instance.
  1. Other methods:
  • Buffer.isBuffer(obj): Checks whether an object is a Buffer instance.
  • Buffer.concat(list[, totalLength]): Concatenate a set of Buffer instances or byte arrays to form a new Buffer instance.

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

View original text


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

sh
npm i jsdom

jsdom is a library that simulates a browser environment and can use the DOM API in Node.js

Simple case

js
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.

Figure 29 for Node.js

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

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

Figure 30 for Node.js

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

Figure 31 for Node.js

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.

View original text


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

js
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

js
path.win32.basename("C:\temp\myfile.html")

Return to myfile.html

path.dirname

This API and basename complement each other exactly

js
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.

js
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

js
path.join("/foo", "/cxk", "/ikun")
// /foo/cxk/ikun

Can support .. ./ ../operators

js
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

js
path.resolve("/aaa", "/bbb", "/ccc")
//   /ccc

Pass in absolute path + relative path

js
path.resolve(__dirname, "./index.js")
//  /User/xiaoman/DeskTop/node/index.js

If only relative paths are passed in

js
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

js
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

js
path.format({
  root: "/",
  dir: "/home/user/documents",
  base: "file.txt",
  ext: ".txt",
  name: "file",
})
// /home/user/dir/file.txt

View original text


Nodejs Chapter 13 (os)

Nodejs os module can interact with the operating system

js
var os = require("node:os")
Serial numberAPIFunction
1os.type()It returns 'Linux' on Linux, 'Darwin' on macOS, and 'Windows_NT' on Windows
2os.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'
3os.release()Returns the version of the operating system, such as 10.xxxx win10
4os.homedir()Return to the user directory. For example, c:\user\xiaoman. The principle is windows echo %USERPROFILE% posix $HOME
5os.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

js
const os = require("node:os")
os.cpus()
js
;[
  {
    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.

Figure 32 for Node.js

Get network information

js
const os = require("node:os")
os.networkInterfaces()
js
{
  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 is true, 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 entire 127.0.0.0 network.

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.

js
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")

View original text


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.

Figure 33 for Node.js

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.

Figure 34 for Node.js

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.

js
{
    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.

Figure 35 for Node.js

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.

js
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.

Figure 36 for Node.js

Environment variable scenario

Distinguish between development environment and production environment

js
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

Figure 37 for Node.js

His principle is that if it is windows, call SET. If it is posix, call export to set environment variables.

sh
set NODE_ENV=production  #windows
export NODE_ENV=production #posix

View original text


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.

  1. spawn execution command
  2. exec execute command
  3. execFile executes an executable file
  4. fork creates node child process
  5. execSync execution command synchronous execution
  6. execFileSync executes the executable file synchronously
  7. spawnSync execution command synchronous execution

usage

  • exec
sh
child_process.exec(command, [options], callback)

Get nodejs version number

js
exec("node -v", (err, stdout, stderr) => {
  if (err) {
    return err
  }
  console.log(stdout.toString())
})

options configuration items

txt
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.

js
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

js
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

cmd
echo '开始'

mkdir test

cd ./test

echo console.log("test1232131") >test.js

echo '结束'

node test.js

Use execFile to execute this

js
execFile(path.resolve(process.cwd(), "./bat.cmd"), null, (err, stdout) => {
  console.log(stdout.toString())
})

Figure 38 for Node.js

  • 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.

js
//                       命令      参数  options配置
const { stdout } = spawn("netstat", ["-an"], {})

//返回的数据用data事件接受
stdout.on("data", (steram) => {
  console.log(steram.toString())
})

Figure 39 for Node.js

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

js
const { fork } = require("child_process")

const testProcess = fork("./test.js")

testProcess.send("我是主进程")

testProcess.on("message", (data) => {
  console.log("我是主进程接受消息111:", data)
})

test.js

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.

Figure 40 for Node.js

View original text


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:
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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

ffmpeg.p2hp.com/download.ht…

Figure 41 for Node.js

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

Figure 42 for Node.js

Subprocess cooperates with ffmpeg

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

Figure 43 for Node.js

  1. Add watermark

-vf is video filter

drawtext adds text fontsize size xy vertical and horizontal direction fontcolor color text watermark copy Lower All

js
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" }
)

Figure 44 for Node.js

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

js
const { execSync } = require("child_process")

execSync(`ffmpeg -ss 10 -to 20 -i test.mp4  test3.mp4`, { stdio: "inherit" })
  1. Extract audio from video
js
const { execSync } = require("child_process")
execSync(`ffmpeg -i test.mp4 test.mp3`, { stdio: "inherit" })

Figure 45 for Node.js

  1. Remove watermark

w h width and height xy vertical horizontal coordinate Filter parameters used by delogo to remove watermarks

js
const { execSync } = require("child_process")

execSync(`ffmpeg -i  test2.mp4 -vf delogo=w=120:h=30:x=10:y=10 test3.mp4`, {
  stdio: "inherit",
})

Figure 46 for Node.js

View original text


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.

js
fs.mkdir("/tmp/a/apple", { recursive: true }, (err) => {
  if (err) throw err
})
js
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

Figure 47 for Node.js

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

js
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

js
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

js
event.setMaxListeners(20)

I only want to monitor once. Even if emit is dispatched multiple times, it will only be triggered once.

js
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

js
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

Figure 48 for Node.js

Open the nodejs source code and search for the function setupProcessObject

Figure 49 for Node.js

  1. It first introduces the event module
  2. Get the prototype object of process
  3. Set the prototype object of evnet to the prototype object of process
  4. And rebind the context
  5. Mount the process to globalThis so we can access this API globally

View original text


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.

juejin.cn/post/727704…

For example, the exec we talked about before

Get Node version

js
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.

js
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

  1. The first step of Promiseify is to return a new function
js
const promiseify = () => {
  return () => {}
}
  1. promiseify accepts a function, and only accepts real parameters in the returned function, and then returns a promise
js
const promiseify = (original) => {
  return (...args) => {
    return new Promise((resolve, reject) => {})
  }
}
  1. 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.
js
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.

js
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

js
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: String will be used to convert all values except BigInt, Object and -0. The BigInt value will be represented by n, and objects without a user-defined toString function are checked using util.inspect() with option { depth: 0, colors: false, compact: 3 }.
  • %d: Number will be used to convert all values except BigInt and Symbol.
  • %i: parseInt(value, 10) for all values ​​except BigInt and Symbol.
  • %f: parseFloat(value) for all values except Symbol.
  • %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 to util.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 to util.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

js
util.format(format, [args])

Example format a string

js
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.

js
util.format(1, 2, 3)
//1 2 3

View original text


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.

pngquant.com/

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:

  1. First, pngquant builds a histogram to count the color distribution in the image.
  2. 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.
  3. pngquant uses a perceptual model to give less weight to noisier areas in the image to build a more accurate histogram.
  4. 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.
  5. Finally, to generate the optimal palette, pngquant corrects the colors using Voronoi iteration (K-means) to ensure local optima.
  6. 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.

  1. Initialization: We treat each pixel in the image as a color point and put them into an initial color bucket.
  2. Select the partition bucket: Select a color channel with the largest range in the initial color bucket, assuming we select the red channel.
  3. 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)

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

js
import { exec } from "child_process"
exec("pngquant 73kb.png --output test.png")

73kb after compression 22kb

js
import { exec } from "child_process"
exec("pngquant 73kb.png --quality=82 --output test.png")

Quality means the bigger the 0-100, the better.

js
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.

View original text


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

js
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())
  1. fs supports both synchronous and asynchronous modes. With the addition of Sync fs, the code will be run in a synchronous manner, which will block the following code. Without Sync, the asynchronous mode will not block.
  2. fs has a new promise version. You only need to add /promise after the imported package, and fs can support promise callbacks.
  3. fs returns a buffer binary data. Every two hexadecimal digits represent one byte.
js
<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.
js
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

js
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.

js
fs.mkdir("path/test/ccc", { recursive: true }, (err) => {})

Delete folders. If recursive is turned on, all folders will be deleted recursively.

js
fs.rm("path", { recursive: true }, (err) => {})

Rename the file. The first parameter is the original name. The second parameter is the new name.

js
fs.renameSync("./test.txt", "./test2.txt")

Monitor file changes and return the monitored events such as change, and the monitored content filename

js
fs.watch("./test2.txt", (event, filename) => {
  console.log(event, filename)
})

Source code analysis

github.com/libuv/libuv

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.

Figure 50 for Node.js

mkdir example

cc
// 创建目录的异步操作函数,通过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

js
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.

View original text


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
js
const fs = require("node:fs")

fs.writeFileSync("index.txt", "java之父\n余胜军")
  1. The file written by the first parameter
  2. The content written in the second parameter
  3. 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.

js
fs.writeFileSync("index.txt", "\nvue之父\n鱿鱼须", {
  flag: "a",
})
txt
java之父
余胜军
vue之父
鱿鱼须

Second way

js
const fs = require("node:fs")

fs.appendFileSync("index.txt", "\nunshift创始人\n麒麟哥")

You can also add content using appendFileSync

Writable stream

js
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.

js
fs.linkSync("./index.txt", "./index2.txt") //硬链接

fs.symlinkSync("./index.txt", "./index3.txt", "file") //软连接

The functions and uses of hard links are as follows:

  1. 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.
  2. 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.
  3. 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:

  1. 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.
  2. 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.
  3. 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.

View original text


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

js
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

js
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

js
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:

  1. 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.
  2. 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.
  3. 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

  1. We can avoid clear text transmission of passwords by using md5 encryption or sha256
  2. 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.

View original text


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

  1. Project structure: Scaffolding defines the directory structure of the project, including source code, configuration files, static resources, etc.
  2. 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.
  3. 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.
  4. Dependency management: Scaffolding can help developers manage project dependencies and automatically install and configure required libraries and tools.
  5. Code generation: Scaffolding can generate common code structures, such as components, modules, routing, etc., to improve development efficiency.
  6. Configuration management: Scaffolding can provide some default configuration options and allow developers to customize configurations as needed.

Figure 51 for Node.js

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

sh
npm link

Figure 52 for Node.js

Figure 53 for Node.js

View original text


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

  1. 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.
  2. 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.
  3. 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.

scss
<% 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 &lt; &gt; &amp;

Therefore, when using <%=, it is best to ensure that the content does not contain HTML characters.

xml
const text = '<p>你好你好</p>'
<h2><%= text %></h2> // 输出 &lt;p&gt;你好你好&lt;/p&gt; 插入 <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

css
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.

less
// 当前模版路径:./views/tmp.ejs
// 引入模版路径:./views/user/show.ejs
<ul>
  <% users.forEach(function(user){ %>
    <%- include('user/show', {user: user}); %>
  <% }); %>
</ul>

5. Conditional judgment

erlang
<% if (condition1) { %>
  ...
<% } %>

<% if (condition1) { %>
  ...
<% } else if (condition2) { %>
  ...
<% } %>

// 举例
<% if (a && b) { %>
  <p>可以直接放 html 内容</p>
<% } %>

<% if (a && b) { %>
  <% console.log('也可以嵌套任意ejs模版语句') %>
<% } %>

6. Loop

ini
<% 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.

ejs
<!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

js
 ### 标题
 - test

Convert md to html

js
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

js
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.

css
/* 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
js
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

Figure 54 for Node.js

Figure 55 for Node.js

View original text


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:

  1. Data compression: Use the zlib module 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.
  2. Data decompression: The zlib module also provides a decompression function for compressed data, which can restore the original data before compression.
  3. Stream compression: The zlib module 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.
  4. Compression format support: zlib module 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)

js
// 引入所需的模块
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

js
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

js
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

js
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

  1. 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.
  2. 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.
  3. 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.
  4. 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)

js
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)

js
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)

View original text


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.

  1. 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.
  2. 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.
  3. 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.
  4. 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

js
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?

js
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

js
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?

Figure 56 for Node.js

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]

http
# 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

View original text


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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

Figure 57 for Node.js

Code implementation

Library used http-proxy-middleware

sh
npm install http-proxy-middleware

Root directory custom configuration file

xm.config.js

Configure proxy proxy

js
module.exports = {
  server: {
    proxy: {
      //代理的路径
      "/api": {
        target: "http://localhost:3000", //转发的地址
        changeOrigin: true, //是否有跨域
      },
    },
  },
}

index.js implementation layer

js
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

js
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

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.

Figure 58 for Node.js

View original text


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:

  1. 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.
  2. 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.
  3. 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:

js
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

txt
-   文本文件:

    -   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:多部分表单数据

View original text


Nodejs Chapter 28 (Mail Service)

Email service plays an important role in our work

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

sh
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

yaml
pass: 授权码 | 密码
user: xxxxx@qq.com 邮箱账号
js
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

wx.mail.qq.com/list/readte…

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

Figure 59 for Node.js

Figure 60 for Node.js

Test sending

http
POST http://localhost:3000/send/mail HTTP/1.1
Content-Type: application/json

{
    "to":"xxxxx@qq.com",
    "subject":"标题",
    "text":"我想你了,xxxxxx"
}

Figure 61 for Node.js

View original text


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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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
js
import express from "express"

const app = express() //express 是个函数

app.listen(3000, () => console.log("Listening on port 3000"))

-Write get post interface

js
app.get("/", (req, res) => {
  res.send("get")
})

app.post("/create", (req, res) => {
  res.send("post")
})
  • Accept parameters from the front end
js
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.

txt
src
 --user.js
 --list.js
app.js

src/user.js

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

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
sh
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

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

js
import express from "express"
import User from "./src/user.js"
import loggerMiddleware from "./middleware/logger.js"
const app = express()
app.use(loggerMiddleware)

Figure 62 for Node.js

View original text


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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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
js
import express from "express"

const app = express()
//自定义前缀   初始化目录
app.use("/assets", express.static("static"))

app.listen(3000, () => {
  console.log("listening on port 3000")
})

Figure 63 for Node.js

Figure 64 for Node.js

Add anti-leeching

Anti-leeching is generally mainly about verifying host or referer

js
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

Figure 65 for Node.js

localhost has permissions

Figure 66 for Node.js

View original text


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

http
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
js
fetch("http://localhost:3000/info")
  .then((res) => {
    return res.json()
  })
  .then((res) => {
    console.log(res)
  })
  • Express writes a get interface
js
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.

Figure 67 for Node.js

At this time, we need back-end support to allow cross-domain request resources to be released.

js
Access-Control-Allow-Origin: * | Origin

Add the following Response Header to allow localhost 5500 access

js
app.use("*", (req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "http://localhost:5500") //允许localhost 5500 访问
  next()
})

Result returned

Figure 68 for Node.js

Request header

By default, cors only supports the client to send the following nine request headers to the server.

tips no application/json

  1. Accept: Specify the content types that the client can handle.
  2. Accept-Language: Specifies the natural language preferred by the client.
  3. Content-Language: Specifies the natural language of the request or response entity.
  4. Content-Type: Specifies the media type of the request or response entity.
  5. DNT (Do Not Track): Indicates that the client does not want to be tracked.
  6. Origin: Indicates the source of the request (protocol, domain name and port).
  7. User-Agent: Contains information about the user agent that initiated the request.
  8. Referer: Indicates the source URL of the current request.
  9. 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

js
;("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

js
app.patch("/info", (req, res) => {
  res.json({
    code: 200,
  })
})

Send patch

js
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.

Figure 69 for Node.js

Modify as follows

js
;("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,PATCH")

Figure 70 for Node.js

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.

  1. 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.
  2. 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.
  3. 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
js
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
js
app.post("/info", (req, res) => {
  res.json({
    code: 200,
  })
})

Found an error reported

Figure 71 for Node.js

Because application/json does not belong to the cors category and needs manual support

js
;("Access-Control-Allow-Headers", "Content-Type")

Figure 72 for Node.js

Figure 73 for Node.js

Custom response header

When we make demands, we will definitely encounter back-end custom response headers

js
app.get("/info", (req, res) => {
  res.set("xmzs", "1")
  res.json({
    code: 200,
  })
})

Figure 74 for Node.js

How does the front end read it?

js
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.

js
app.get("/info", (req, res) => {
  res.set("xmzs", "1")
  res.setHeader("Access-Control-Expose-Headers", "xmzs")
  res.json({
    code: 200,
  })
})

Figure 75 for Node.js

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-stream to become sse event event name data data sent
js
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

js
const sse = new EventSource("http://localhost:3000/sse")
sse.addEventListener("test", (event) => {
  console.log(event.data)
})

Figure 76 for Node.js

View original text


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:

  1. 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.
  2. Table: Data in the database is organized into tables. A table consists of rows and columns, with rows representing records and columns representing fields.
  3. SQL: MySQL uses Structured Query Language (SQL) for database operations. SQL is a language used to define, manipulate, and query databases.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.
  9. 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.
  10. Backup and recovery: MySQL provides tools and commands to back up and restore the database to ensure data security and reliability.

Figure 77 for Node.js

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

www.mysql.com/

Figure 78 for Node.js

scroll below

Figure 79 for Node.js

Figure 80 for Node.js

Figure 81 for Node.js

Figure 82 for Node.js

Default port 3306

Figure 83 for Node.js

Set password

Figure 84 for Node.js

Add mysql service and remember the name (MySQL83)

Figure 85 for Node.js

Just keep going down

Figure 86 for Node.js

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

Figure 87 for Node.js

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.

Figure 88 for Node.js

Then configure the environment variables

Figure 89 for Node.js

Test Mysql and enter the password

sh
mysql -uroot -p

Figure 90 for Node.js

success

Visual tool installation

Open VScode

Select the extension, search database and install Database Client

Figure 91 for Node.js

Figure 92 for Node.js

Create new library

Figure 93 for Node.js

Figure 94 for Node.js

Figure 95 for Node.js

Create new table

Figure 96 for Node.js

Insert data

Figure 97 for Node.js

Figure 98 for Node.js

Figure 99 for Node.js

View original text


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

sql
create database 库名

Figure 100 for Node.js

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

Figure 101 for Node.js

Avoid this problem if not exists

sql
create database if not exists `xiaoman`

Figure 102 for Node.js

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

sql
create database `xiaoman`
    default character set = 'utf8mb4';

Data table

  • Create table
sql
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 (

  1. id field name int data type represents numeric type NOT NULL (cannot be empty) AUTO_INCREMENT (id increases automatically) PRIMARY KEY (id is the primary key)
  2. name (field name) varchar(100) string type 100 characters COMMENT (comment)
  3. age (field name) int data type represents the numeric type COMMENT (comment)
  4. create_time (field name) timestamp (timestamp) DEFAULT CURRENT_TIMESTAMP (auto-fill creation time)

)

Figure 103 for Node.js

  • Modify table name
sql
ALTER TABLE `user` RENAME `user2`;

Figure 104 for Node.js

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

Figure 105 for Node.js

  • Delete columns
sql
ALTER TABLE `user` DROP COLUMN `hobby`;

Figure 106 for Node.js

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

Figure 107 for Node.js

View original text


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

sql
SELECT `name` FROM `user`;

Query multiple columns, separated by commas

sql
SELECT `name`,`id` FROM `user`;

Figure 108 for Node.js

Query all columns *

sql
SELECT *  FROM `user`;

Figure 109 for Node.js

Column alias as

sql
SELECT `name` as `user_name`,`id` as `user_id` FROM `user`;

Figure 110 for Node.js

Sort

ORDER BY [field name] desc Descending order (from large to small) asc Ascending order (from small to large)

sql
SELECT *  FROM `user` ORDER BY id DESC;

Figure 111 for Node.js

Limit query results

limit [start line] [limit number of items]

When using limit, it starts from 0, just like an array.

sql
SELECT *  FROM `user` LIMIT 1,3

Figure 112 for Node.js

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

sql
SELECT *  FROM `user` WHERE name = "大满";

Figure 113 for Node.js

Joint query with multiple conditions

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

Figure 114 for Node.js

  • 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.

sql
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.

sql
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.
sql
SELECT * FROM `user` WHERE name LIKE '%满%';

Figure 115 for Node.js

View original text


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.

sql
INSERT INTO user(`name`,`hobby`,`age`) VALUES('xiaoman','basketball',18)

Figure 116 for Node.js

Insert null value

When designing the table structure, we allow name age hobby to be null, so we can also insert null values.

sql
INSERT INTO user(`name`,`hobby`,`age`) VALUES(NULL,NULL,NULL)

Figure 117 for Node.js

Insert multiple pieces of data separated by commas

sql
INSERT INTO user(`name`,`hobby`,`age`) VALUES(NULL,NULL,NULL),('xiaoman','basketball',18)

Figure 118 for Node.js

Delete

Delete the record with id 11

sql
DELETE FROM `user` WHERE id = 11;

Figure 119 for Node.js

Batch delete

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

Figure 120 for Node.js

Update data

The updated field uses = assignment, where determines the updated regulations

sql
UPDATE `user` SET name='麒麟哥',age=30,hobby='篮球' WHERE id = 12;

Figure 121 for Node.js

View original text


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.

  1. 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;
  2. 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;
  3. 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';
  4. 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;
  5. 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;
  6. 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

sql
SELECT age + 100 FROM `user`;

Figure 122 for Node.js

If you want to change the column name, you can use as

sql
SELECT age + 100 as age FROM `user`;

Figure 123 for Node.js

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:

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

Figure 124 for Node.js

  • Sum

Figure 125 for Node.js

  • String concatenation

Figure 126 for Node.js

  • Get the total number

Figure 127 for Node.js

View original text


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

Figure 128 for Node.js

user table data

Figure 129 for Node.js

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.

sql
SELECT * FROM `photo` WHERE `user_id` = (SELECT id FROM `user` WHERE name = '小满')

Figure 130 for Node.js

Join table

Mysql's connected tables are divided into inner joins, outer joins, and cross joins

  1. 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-called Inner Connection.
  2. 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.
  3. Cross-connection refers to a connection without any connection conditions between two or more tables. Simply put, Cross-connection allows you to query all possible combinations.

Inner join

sql
SELECT * FROM `user`, `photo` WHERE `user`.`id` = `photo`.`user_id`

Figure 131 for Node.js

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.

sql
SELECT * FROM `user` LEFT JOIN `table` ON `user`.`id` = `table`.`user_id`

Figure 132 for Node.js

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.

sql
SELECT * FROM `user` RIGHT JOIN `table` ON `user`.`id` = `table`.`user_id`

Figure 133 for Node.js

View original text


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

sh
npm install mysql2 express js-yaml
  1. mysql2 is used to connect to mysql and write sq statements
  2. Express is used to provide interfaces for additions, deletions and modifications.
  3. js-yaml is used to write configuration files

Write code

db.config.yaml

yaml
db:
  host: localhost #主机
  port: 3306 #端口
  user: root #账号
  password: "123456" #密码 一定要字符串
  database: xiaoman # 库

index.js

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

http
# 查询全部
 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

Figure 134 for Node.js

View original text


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.

knexjs.org/guide/query…

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.

sh
#安装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

js
import knex from "knex"
const db = knex({
  client: "mysql2",
  connection: config.db,
})
yaml
db:
  user: root
  password: "123456"
  host: localhost
  port: 3306
  database: xiaoman

Define table structure

js
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

js
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.

js
//伪代码
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() //回滚事务
  }
})

View original text


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:

  1. 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.
  2. 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.
  3. 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.
  4. 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

  1. Install Prisma CLI:
  • Install using npm: run npm install -g prisma.
  • Install using yarn: run yarn global add prisma.
  1. Initialize project
  • Use prisma init --datasource-provider mysql

At this point, a basic directory will be created and generated.

Figure 135 for Node.js

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

js
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.

sh
prisma migrate dev

Figure 136 for Node.js

Implement addition, deletion, modification and query

ts
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}`)
})

View original text


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.

  1. 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.
  2. 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.
  3. 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.

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

  1. inversify + reflect-metadata implements dependency injection official website
  2. Interface writing express Official website
  3. Connection tool inversify-express-utils Document
  4. orm framework prisma official website
  5. dto class-validator + class-transformer Document

Project structure

Create a new app folder

Build prisma project through prisma init --datasource-provider mysql As mentioned in the previous chapter

juejin.cn/post/733718…

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

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

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

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

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

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.

json
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"strict": false,

View original text


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 (.):

  1. Header: Contains information such as the type of token and the encryption algorithm used. Usually represented by Base64 encoding.
  2. 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.
  3. 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:

  1. The user authenticates by providing valid credentials (such as username and password).
  2. The server verifies the credentials and generates a JWT in response. JWT contains the user's identity information and other necessary data.
  3. The server sends the JWT to the client.
  4. In subsequent requests, the client puts the JWT into the request header or other appropriate location.
  5. 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

  1. passport passport is a popular Node.js library for authentication and authorization
  2. passport-jwt Passport-JWT is a plug-in of the Passport library to support authentication and authorization using JSON Web Token (JWT)
  3. jsonwebtoken library for generating tokens

Code writing

Use the code from the previous chapter to add the jwt directory Previous chapter code

Figure 137 for Node.js

src/jwt/index.ts

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

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

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

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)

Figure 138 for Node.js

  • Successful verification display (with token)

Figure 139 for Node.js

View original text


Nodejs Chapter 43 (redis)

Figure 140 for Node.js 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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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

  1. Installation package form
  • Send me a private message to ask for the installation package

Figure 141 for Node.js

  • Configure to environment variables Figure 142 for Node.js
  • Add to windows service (cmd administrator mode)
sh
redis-server.exe --service-install [配置文件] --loglevel verbose
#例如
redis-server.exe --service-install redis.conf --loglevel verbose
  1. wsl installation
  • redis.io/docs/instal…
  • cmd administrator mode execute wsl --update to upgrade wsl version wsl --set-default-version 2 to set wsl version 2
  • Open the Microsoft Store and search for wsl to install an Ubuntu

Figure 143 for Node.js

Figure 144 for Node.js

  • Then follow the official website and execute the following commands

Figure 145 for Node.js

Mac,Linux installation

  1. brew install redis Start redis redis-server Connect redis redis-cli
  2. wget https://download.redis.io/redis-stable.tar.gz

Compile source files

sh
tar -xzvf redis-stable.tar.gz
cd redis-stable
make
make install

Start redis

sh
redis-server

Visualization tools

Open the Vscode extension and search for Database Client

Figure 146 for Node.js

Figure 147 for Node.js

Figure 148 for Node.js

View original text


Nodejs Chapter 44 (Basic use of redis)

String operations

sh
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.
  1. Set the value of the key name "name" to "John":
sh
SET name "xiaoman"
  1. Set the value of the key name "counter" to 10, and set the expiration time to 60 seconds:
sh
SET counter 10 EX 60
  1. Only when the key name "status" does not exist, set its value to "active":
sh
SET status "active" NX
  1. Only if the key name "score" already exists, increase its value by 5:
sh
SET score 5 XX
  1. Set the value of the key named "message" to "Hello" and return the old value:
sh
SET message "Hello" GET
  1. Delete the key named "name":
sh
DEL name
  1. Delete multiple key names in batches:
sh
DEL key1 key2 key3
  1. Delete non-existing key names without reporting an error, and return the number of deleted keys as 0:
sh
DEL non_existing_key

Figure 149 for Node.js

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.

  1. Add members to the collection:
sh
SADD fruits "apple"
SADD fruits "banana"
SADD fruits "orange"
  1. Get all members in the collection:
sh
SMEMBERS fruits

Output result:

arduino
1) "apple"
2) "banana"
3) "orange"
  1. Check whether the member exists in the collection:
sh
SISMEMBER fruits "apple"

Output result:

bash
(integer) 1
  1. Remove members from the collection:
sh
SREM fruits "banana"

Output result:

sh
(integer) 1
  1. Get the number of members in the set:
sh
SCARD fruits

Output result:

bash
(integer) 2
  1. Get random members:
sh
SRANDMEMBER fruits

Output result:

arduino
"apple"
  1. Find the union of multiple sets:
sh
SUNION fruits vegetables

Output result:

arduino
1) "apple"
2) "orange"
3) "tomato"
4) "carrot"
  1. Find the intersection of multiple sets:
sh
SINTER fruits vegetables

Output result:

arduino
"apple"
  1. Find the difference of multiple sets:
sh
SDIFF fruits vegetables

Output result:

arduino
"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.

  1. Set the field value in the hash table:
perl
HSET obj name "John"
HSET obj age 25
HSET obj email "john@example.com"
  1. Get the field value in the hash table:
code
HGET obj name

Output result:

arduino
"John"
  1. Set the values of multiple fields at once:
perl
HMSET obj name "John" age 25 email "john@example.com"
  1. Get the values of multiple fields:
code
HMGET obj name age email

Output result:

perl
1) "John"
2) "25"
3) "john@example.com"
  1. Get all fields and values in the hash table:
code
HGETALL obj

Output result:

perl
1) "name"
2) "John"
3) "age"
4) "25"
5) "email"
6) "john@example.com"
  1. Delete fields in the hash table:
code
HDEL obj age email

Output result:

bash
(integer) 2
  1. Check whether the specified field exists in the hash table:
code
HEXISTS obj name

Output result:

bash
(integer) 1
  1. Get all fields in the hash table:
code
HKEYS obj

Output result:

arduino
1) "name"
  1. Get all values in the hash table:
code
HVALS obj

Output result:

arduino
1) "John"
  1. Get the number of fields in the hash table:
code
HLEN obj

Output result:

bash
(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.

  1. Add elements:
arduino
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 into Head of 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 into End of the list in sequence. If the list does not exist, a new list will be automatically created before performing the operation.
  1. Get elements:
arduino
LINDEX key index  // 获取列表中指定索引位置的元素
LRANGE key start stop  // 获取列表中指定范围内的元素
  1. Modify elements:
arduino
LSET key index newValue  // 修改列表中指定索引位置的元素的值
  1. Delete elements:
arduino
LPOP key  // 从列表的左侧移除并返回第一个元素
RPOP key  // 从列表的右侧移除并返回最后一个元素
LREM key count value  // 从列表中删除指定数量的指定值元素
  1. Get the list length:
arduino
LLEN key  // 获取列表的长度

View original text


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:

  1. 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".
  2. 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".
  3. 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".
  4. 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.".
  5. 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.".

Figure 150 for Node.js

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.

  1. 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.
  2. 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.
  3. 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.
  4. 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:

  1. Use the MULTI command to start a transaction.
  2. Add the commands to be executed to the transaction queue.
  3. If necessary, use the WATCH command to watch the keys.
  4. Execute the EXEC command to execute the transaction. Redis will execute the commands in the order in the queue and return the execution results.
  5. 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.

sh
# 连接Redis
redis-cli

# 开启事务
MULTI

# 添加命令到事务队列
SET key1 value1
GET key2

# 执行事务
EXEC

Figure 151 for Node.js

View original text


Nodejs Chapter 46 (redis persistence)

redis persistence

Redis provides two persistence methods:

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

Figure 152 for Node.js

find save

Figure 153 for Node.js

He provided three cases

  1. A snapshot will be triggered if a change is made within 3600 seconds, that is, once an hour.
  2. Within 300 seconds, which is 5 minutes, a snapshot will be taken if 100 modifications are made.
  3. 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.

Figure 154 for Node.js

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

Figure 155 for Node.js

AOF usage

  1. Set the value of the appendonly configuration item to yes: By default, the value of this configuration item is no, indicating that AOF persistence is not enabled. Modify its value to yes to enable AOF persistence.

Figure 156 for Node.js

View original text


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.

Figure 157 for Node.js

The following is the general workflow of Redis master-slave replication:

  1. 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 replicaof configuration option or the slaveof configuration option to specify a slave server.
  2. 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 SYNC command or partial copy (incremental copy) by sending the PSYNC command.
  3. 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.
  4. 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.
  5. Replication persistence: After receiving data from the server, it will be saved on the local disk to maintain data consistency after restarting.
  6. 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.
  7. 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.
  8. 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

conf
bind 127.0.0.1 #ip地址
port 6378 #端口号
daemonize yes #守护线程静默运行
replicaof 127.0.0.1 6379 #指定主服务器

Start the slave server

sh
redis-server ./redis-6378.conf 指定配置文件

Open the slave server cli

css
redis-cli -p 6378

Start the main server

code
redis-cli 直接启动默认就是主服务器的配置文件

The master writes a value

arduino
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

Figure 158 for Node.js

View original text


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:

  1. 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.
  2. Promises and async/await support: ioredis uses promises and supports async/await syntax, making writing asynchronous code and processing Redis commands more readable.
  3. 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.
  4. Lua script: ioredis allows you to use the eval and evalsha commands 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.
  5. 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 BRPOP and BLPOP, allowing you to wait for items to be pushed to the list and pop them atomically.
  6. 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

sh
npm i ioredis

Connect redis

js
import Ioredis from "ioredis"

const ioredis = new Ioredis({
  host: "127.0.0.1", //ip
  port: 6379, //端口
})
  1. String
js
//存储字符串并且设置过期时间
ioredis.setex("key", 10, "value")
//普通存储
ioredis.set("key", "value")
//读取
ioredis.get("key")
  1. Collection
js
// 添加元素到集合
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)
})
  1. Hash
js
// 设置哈希字段的值
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' }
})
  1. Queue
js
// 在队列的头部添加元素
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

js
// 引入 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")

View original text


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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

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

lua official website

Figure 159 for Node.js

Figure 160 for Node.js

Figure 161 for Node.js

Just choose the corresponding platform and download it.

Figure 162 for Node.js

Once the download is complete, configure the environment variables.

Figure 163 for Node.js

Use lua54 to test it

Figure 164 for Node.js

vscode support

Find the extension and install the following two plug-ins

Figure 165 for Node.js

debug code

Figure 166 for Node.js

View original text


Nodejs Chapter 50 (Basic use of lua)

Figure 167 for Node.js

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.
lua
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.
lua
--local 定义局部变量
local xiaoman = 'xmzs'

print(xiaoman)

conditional statement

In Lua, conditional judgment statements can be implemented using the if, elseif and else keywords

lua
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

lua
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

  1. nil: Indicates invalid value or missing value.
  2. boolean: represents a Boolean value, which can be true or false.
  3. number: represents numbers, including integers and floating point numbers.
  4. string: represents a string, consisting of a character sequence.
  5. table: represents a table, an associative array used to store and organize data.
  6. function: represents a function, used to encapsulate executable code blocks.
  7. userdata: Represents user-defined data type, usually used interactively with C language library.
  8. thread: represents coroutine, used to implement multi-thread programming.
  9. metatable: Represents a metatable, used to define the behavior of the table.

Common data type usage

lua
type = false --布尔值
type = nil --就是null
type = 1 --整数
type = 1.1 --浮点型
type = 'xmzs' --字符串
print(type)

String concatenation ..

lua
local s = 'xm'
local m = 'zs'
print(s .. m)

table can describe objects and arrays

lua index starts from 1

lua
--对象
table = {
    name = "xiaoman",
    age = 18
}
print(table.name)
print(table.age)
--数组
arr = {1,2,3,4,6}
print(arr[1])

loop

lua
for i = 1, 10, 3 do --开始 结束 步长  步长就是递增数量
    print(i)
end

Loop table

lua
arr = {name = "hello", age = 18, sex = "male"}
for k, v in pairs(arr) do
    print(k, v)  --key 和 value 也就是 name 和 hello ...
end

loop array

lua
local arr = {10,20,30}

for i, v in ipairs(arr) do
    print(i,v)
end

Modularity

test.lua exposes a method add

lua
local M = {}

function M.add(a, b)
    return a + b
end

return M

index.lua introduces the file and calls the add method

lua
local math = require('test')

local r = math.add(1, 2)

print(r)

View original text


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

css
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.
js
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.
lua
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

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>
    <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

Figure 168 for Node.js

Normal click

Figure 169 for Node.js

View original text


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:

  1. 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.
  2. 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.
  3. 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

sh
npm install node-schedule

node-schedule document

Generally, scheduled tasks use cron expression 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:

markdown
---

┬ ┬ ┬ ┬ ┬ ┬
│ │ │ │ │ │
│ │ │ │ │ └── 星期(0 - 6,0表示星期日)
│ │ │ │ └───── 月份(1 - 12)
│ │ │ └────────── 日(1 - 31)
│ │ └─────────────── 小时(0 - 23)
│ └──────────────────── 分钟(0 - 59)
└───────────────────────── 秒(0 - 59)
DomainRequiredValue rangeSpecial characters
Seconds SecondsYes[0, 59]* , - /
MinutesYes[0, 59]* , - /
HoursYes[0, 23]* , - /
Date DayofMonthYes[1, 31]* , - / ? L W
Month MonthYes[1, 12] or [JAN, DEC]*, - /
DayofWeekIs[1, 7] or [MON, SUN]. If the expression [1, 7] is used, 1 represents Monday and 7 represents Sunday.* , - / ? L #
Year YearNo1970+- * /

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, */5 means 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, L for the last day, W for 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)

js
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

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",
}

Figure 170 for Node.js

aid uid cookie

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

Figure 171 for Node.js

cookie

Figure 172 for Node.js

View original text


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

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

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

sh
npm install @serverless-devs/s -g

@serverless-devs/sdocs

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.

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

Figure 173 for Node.js

  1. Add key

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

sh
s config add

Figure 174 for Node.js

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

Figure 175 for Node.js

Check whether the key is correct. If the information can be output, it is correct.

sh
s config get -a [别名]

Figure 176 for Node.js

  1. Create a project

Just run the s command directly

sh
s

Figure 177 for Node.js

Open the generated project

Figure 178 for Node.js

Execute in directory

code
s deploy

Upload successful

Figure 179 for Node.js

fcnext.console.aliyun.com/cn-beijing/…

Visit this link to find your function

Figure 180 for Node.js

Figure 181 for Node.js

call this function

Figure 182 for Node.js

Figure 183 for Node.js

View original text


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.

Figure 184 for Node.js

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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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

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

js
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

js
import net from "net"

const client = net.createConnection({
  host: "127.0.0.1",
  port: 3000,
})

client.on("data", (data) => {
  console.log(data.toString())
})
  1. Implement http protocol from the transport layer

Create a TCP service

js
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

  1. close triggers once the socket is completely closed
  2. connect Triggered when the socket connection is successfully established
  3. data triggers when data is received
  4. end triggers 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

Figure 185 for Node.js

You can see that the browser sent an http get request. We can return relevant content through the keyword get, such as html

js
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")
})

Figure 186 for Node.js

View original text


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.

Figure 187 for Node.js

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.

Figure 188 for Node.js

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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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

sh
npm install socket.io

The browser uses esm

html
<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>

socket.io official website

Chat Room

Figure 189 for Node.js

Figure 190 for Node.js

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>
      * {
        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

js
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")
})

View original text


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 regulations and the website

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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

Nuggets robots.txt rules

Install dependencies

nodejs

sh
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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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

sh
pip install wordcloud #生成词云图
pip install jieba #中文分词
  1. 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

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

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)

Figure 191 for Node.js

View original text


Nodejs Chapter 57 (addon)

Figure 192 for Node.js

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

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

  1. Use Nodejs libraries written in C++ such as node-sass node-jieba, etc.
  2. CPU-intensive applications
  3. Code protection

Dependencies that need to be installed

c++ editor installation

sh
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

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

json
{
  "targets": [
    {
      "target_name": "cpu", //名称
      "sources": ["cpu.cpp"], //指定文件
      "include_dirs": [
        "<!@(node -p \"require('node-addon-api').include\")" //引入addon
      ]
    }
  ]
}

index.js

js
const addon = require("./build/Release/cpu.node")
console.log(addon.getScreenSize())
sh
node-gyp configure #生成配置文件
node-gyp build  #打包addon

Figure 193 for Node.js

View original text


Nodejs Chapter 58 (Large File Upload)

Figure 194 for Node.js

In modern websites, more and more personalized pictures and videos are displayed, so our websites generally support file uploads.

File upload plan

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

html
<input id="file" type="file" />
<!--用来上传文件-->

Listen to the change event to obtain the file file and implement a method chunkFun for slicing

js
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.

js
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.

js
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

  1. express helps us start the service and provide an interface
  2. multer reads files and stores
  3. cors solves cross-domain issues

Import module

js
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

  1. up is used to store slices
  2. 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

txt
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

js
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")
})

Figure 195 for Node.js

View original text


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

sh
npm install express #启动服务 提供接口
npm install cors #解决跨域

nodejs full version code

Core knowledge response header

  1. Content-Type specifies the MIME type of the downloaded file
  • application/octet-stream (binary stream data)
  • application/pdf: Adobe PDF file.
  • application/json: JSON data file
  • image/jpeg: JPEG image file
  1. Content-Disposition specifies 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 the filename parameter to specify the name of the downloaded file
  • inline: 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)
js
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")
})

Figure 196 for Node.js

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.

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>
    <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>

Figure 197 for Node.js

View original text


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)

Figure 198 for Node.js

  1. memory cache The memory cache is stored in the browser memory. Generally, when refreshing the web page, you will find many memory caches.
  2. 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

js
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

html
<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

Figure 199 for Node.js

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

js
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!")
})

Figure 200 for Node.js

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

js
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!")
})

Figure 201 for Node.js

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

js
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!")
})

Figure 202 for Node.js

View original text


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

Figure 203 for Node.js

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

Figure 204 for Node.js

  1. Binary Framing: Binary Frame is 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:

  1. Data Frame: used to transmit the actual data of requests and responses.
  2. Headers Frame: Contains header information of the request or response.
  3. Priority Frame: used to specify the priority of the request.
  4. Settings Frame: used to transmit communication parameter settings.
  5. Push Promise Frame: used for the server to actively push resources.
  6. PING Frame: used to detect the activity of the connection.
  7. Reset frame (RST_STREAM Frame): used to reset the data stream or notify errors.

Figure 205 for Node.js

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

Figure 206 for Node.js

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

  1. Generate private key
sh
openssl genrsa -out server.key 1024
  1. Generate a certificate request file (you can delete or keep it after use)
sh
openssl req -new -key server.key -out server.csr
  1. Generate certificate
sh
openssl x509 -req -in server.csr -out server.crt -signkey server.key -days 3650
js
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")
})

View original text


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

Figure 207 for Node.js

00f362cb8318ee9ad5438e77f5c34b3.png

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

  1. epxress starts the service providing interface
  2. mysql2 knex relies on connecting to the database
  3. knex orm framework operates mysql
  4. shortid generates a unique short code

Database design

sql
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

js
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

Figure 208 for Node.js

Visit link redirect to destination URL

Figure 209 for Node.js

View original text


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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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

Figure 210 for Node.js

Software that needs to be installed

  1. Keil uVision5 Write microcontroller code
  2. stcai-isp burning microcontroller program

Microcontroller serial communication programming

c
#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

{54CABAED-23FA-4b91-AF4D-41B6D71FE91B}.png

Nodejs side writing

Install serialport

sh
npm install serialport

Code writing

js
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)

Figure 211 for Node.js

View original text


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:

  1. User-friendliness: Users only need to log in once to access multiple applications, providing a better user experience and convenience.
  2. 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.
  3. 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.

Figure 212 for Node.js

Code writing

  1. Installed dependencies
  • express starts the service writing interface
  • express-session operation cookie
  • jsonwebtoken generates token
  • cors cross domain
  1. 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

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

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

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

html
<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

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

a.gif

View original text


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

  1. Video and audio, prevent one account from being shared, and prevent some account dealers
  2. 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.
  3. 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.
  4. 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

js
{
  id: {
    socket: ws实例
    fingerprint: 浏览器指纹
  }
}
  1. When logging in for the first time, record the user ID, socket information, and browser fingerprint.
  2. 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

js
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

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>
    <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

Figure 213 for Node.js

View original text


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:

  1. 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.
  2. 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.
  3. 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.
  4. 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

  1. express provides interface services
  2. jsonwebtoken generates token
  3. qrcode generates QR code

Flowchart

Figure 214 for Node.js

General logic

js
const status = {
  0: "未授权",
  1: "已授权",
  2: "超时",
}
  1. 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).
  2. On this page, poll the interface to check whether the status is authorized. If it is authorized or times out, stop polling.
  3. 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

  1. mandate.html authorization page
  2. qrcode.html QR code page

index.js nodejs logic code

index.js

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

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

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

Figure 215 for Node.js

View original text


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.

Figure 216 for Node.js

Application scenarios

Using Node.js and OpenAI API, you can implement various applications, such as:

  1. Text generation: Use OpenAI’s text generation capabilities to generate articles, stories, conversations and other content.
  2. Language translation: By calling the OpenAI API, the automatic translation function is realized and one language is translated into another language.
  3. Question answering: Pass the questions raised by users to the OpenAI model to obtain high-quality answers.
  4. Intelligent conversation robot: Build an intelligent conversation robot that can have natural and smooth conversations with users.

Application process

  1. Visit the openAI official website openai.com/
  2. Log in

Figure 217 for Node.js

Figure 218 for Node.js

Apply for key

Figure 219 for Node.js

Figure 220 for Node.js

Figure 221 for Node.js

Code writing

Dependencies that need to be installed

  1. dotenv gets environment variables
  2. openai calls openai capabilities
  3. Express writes interfaces to provide services

Create a new .env file

env
API-KEY = 'openai秘钥'

Create a new index.js file

js
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

Figure 222 for Node.js

Figure 223 for Node.js

View original text


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

  1. Remote Desktop
  2. Remote server operation
  3. Cloud gaming

Environment preparation

python environment installation

www.python.org/downloads/

Figure 224 for Node.js

c++ environment installation

visualstudio.microsoft.com/zh-hans/tha…

Figure 225 for Node.js

Global dependencies

sh
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

  1. screenshot-desktop screenshot
  2. ws real-time transmission
  3. get-pixels gets the image size
  4. 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.

js
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

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

ff.gif

View original text


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

  1. Writing anti-virus software
  2. Daily antivirus use
  3. Real-time protection
  4. Email web scanning
  5. Server antivirus

Engine

clamAV

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:

  1. 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.
  2. Multi-platform support: ClamAV is cross-platform and can run on a variety of operating systems, including Windows, macOS, Linux, FreeBSD, etc.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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

www.clamav.net/downloads

Select the corresponding operating system

Figure 226 for Node.js

windows

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

  1. clamd.conf
  2. freshclam.conf

Copy the contents of the folder to the root directory

Figure 227 for Node.js Figure 228 for Node.js

Then comment out Example in these two files

Figure 229 for Node.js

  1. Update virus database

Execute this command freshclam

09bbe6263958a60031db070cd3f5643.png

Start clamd service

Figure 230 for Node.js

nodejs use

Install clamscan

sh
npm install clamscan
js
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.

Figure 231 for Node.js

View original text


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.

Figure 232 for Node.js

  1. OSS is stored according to Bucket

Figure 233 for Node.js

OSS purchase (Alibaba Cloud demo)

www.aliyun.com/product/oss

  1. Buy a 40G resource package for $4.98 yuan

Figure 234 for Node.js

  1. Create a Bucket after purchasing

Select public reading. If you select private, you need to bring the private key when accessing the picture.

Figure 235 for Node.js

  1. Test uploading pictures

Figure 236 for Node.js Figure 237 for Node.js

Just access it directly

Figure 238 for Node.js

NodejsUpload

Create a secret key nodejs needs to use

Figure 239 for Node.js

OSS official document

sh
npm install ali-oss
js
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

js
//第一个参数上传到OSS文件的名称
//第二个参数本地图片的路径
const result = await client.put("1.jpg", "./1.jpg")
console.log(result)

Download

js
//第一个参数OSS图片名称
//第二个参数下载到本地的路径
await client.get("1.png", path.join(process.cwd(), "./1.png"))

Delete

js
//第一个参数删除存储库文件的名称
const result = await client.delete("1.png")

Third-party authorization

Official document signature

js
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

Figure 240 for Node.js

js
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

Figure 241 for Node.js

View original text


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:

  1. Event Loop: libuv implements Event Cycle Mechanism of 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

Figure 242 for Node.js

Nodejs event loop can be divided into two types, Micro and Macro

macro task

  1. timers Execute settimeout and setInterval
  2. pending callbacks Executing delayed return like IO, timer
  3. idle, prepare idle state Nodejs in-house use without concern
  4. 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
  5. check Execute the setImmediate echo
  6. close callback Execute echoes for example socket.on ('close',...)

microtasks

  1. process.nextTick
  2. promise

Note: Inaccurate timer

We write a case Output 3, 1, 2, not 1, 2, 3. according to the above sequence

Figure 243 for Node.js

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

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

c
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

Figure 244 for Node.js

nodejs V20 test

Figure 245 for Node.js

View original text


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

  1. High Performance: As far as we know, Fastify is one of the fastest web frameworks and we can handle up to 40,000 requests per second depending on the code complexity.
  2. Extensible: Fastify is fully extensible through its hooks, plugins and decorators.
  3. 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.
  4. Logging: Logging is important but costly; we chose Pino, the best logger, to virtually eliminate this cost!
  5. Developer Friendly: This framework is designed to be very expressive and help developers in daily use without sacrificing performance and security.
  6. TypeScript Ready: We work hard to maintain TypeScript type declaration files

Comparison between Fastify and other frameworks

Figure 246 for Node.js

Application scenarios

  1. Gateway layer
  2. One of the only frameworks in Nest
  3. Require high-performance services
  4. Ethereum

Basic usage

Basically the same as express

js
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

  1. method defines the request method, such as get post put, etc.
  2. url matches interface path
  3. 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%
  1. handler request processing function
js
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.

js
fastify.register(plugin, [options])
  1. app is a fastify instance
  2. options are the passed parameters
  3. done control flow is the same as express next
js
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

sh
npm i @fastify/mysql

Connect to database

js
server.register(import("@fastify/mysql"), {
  connectionString: "mysql://root:123456@localhost:3306/xiaoman", //账号,密码,IP,端口,库名
})

Implement a simple add and query

js
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"))

View original text


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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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

sh
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

js
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.

js
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

yaml
node server.js 9001
node server.js 9002

Gateway layer writing

src/index.js

Core function implementation

  1. Proxy service (the configuration item of the proxy service is an array and is registered cyclically, so that the entrance can be unified)
  2. Melting technology (detects whether the service is running normally, and fuses if it hangs up or times out a certain threshold)
  3. Caching technology (the bottom layer is actually Consultation Cache|Strong Cache)
  4. 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.

js
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

Figure 247 for Node.js

Our system can also implement multiple gateway layers depending on the device

Warm reminder: There is not necessarily only one gateway layer.

js
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

js
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

sh
nodemon src/index.js

View original text


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

  1. The monolithic architecture is suitable for small projects with low concurrency (5-10w). In fact, all functions are put into one project.
  2. 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

Figure 248 for Node.js

Architecture implementation

17b2fcb8d9ac764083c001a3ee671db4.jpg

Advantages of microservices

  1. 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.
  2. 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.
  3. 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?

  1. Netflix
  2. Uber
  3. Taobao
  4. Tencent Video
  5. Meituan Group Buying
  6. 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

sh
npm install pnpm -g

Directory structure

js
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

yaml
packages:
  - 'packages/*'
  - 'common

execute

sh
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.

View original text


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

  1. Message: In RabbitMQ, message is the basic unit of delivery. It consists of a message body and optional attributes
  2. Producer: The producer is the sender of the message, which sends the message to the RabbitMQ exchange (Exchange)
  3. Exchange: The exchange receives messages sent from producers and routes the messages to one or more queues according to specific rules.
  4. Queue: The queue is the receiver of messages, which stores messages to be processed. Consumers can get messages from the queue and process them
  5. Consumer Consumer: The consumer is the receiver of the message. It obtains the message from the queue and processes it.

Figure 249 for Node.js


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

Figure 250 for Node.js

After the installation is complete, add an environment variable

Figure 251 for Node.js

ERLANG_HOME -> Corresponding directory such as (D:\erlang\Erlang OTP)

Then add path %ERLANG_HOME%\bin

Figure 252 for Node.js

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

Figure 253 for Node.js

2. Install MQ

Open MQ official website

Figure 254 for Node.js

For example windows

Figure 255 for Node.js

Configure environment variables after installation is complete

Figure 256 for Node.js

Start MQ

Install the MQ plug-in to have a visualization panel

bash
rabbitmq-plugins enable rabbitmq_management

Figure 257 for Node.js

Start MQ command

MQ default port 5672

bash
rabbitmq-server.bat start

Figure 258 for Node.js

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

Figure 259 for Node.js

Nodejs use

We use MQ in Nodejs for nothing more than microservice applications or cross-language communication.

Install dependencies

sh
npm install amqplib

producer.js producer

js
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

js
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.

  1. Queue persistence Starts the queue when the consumer connects: true
  2. Message persistence Sender opens the message when sending

It can even communicate across languages python

py
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

  1. Communication between microservices, or cross-language level communication
  2. 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.
  3. 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

Figure 260 for Node.js

View original text


Nodejs Chapter 76 (MQ Advanced)

Figure 261 for Node.js

The introduction and basic use of MQ have been introduced in the previous chapter and will not be repeated juejin.cn/post/737508…

  1. Message: In RabbitMQ, message is the basic unit of delivery. It consists of a message body and optional attributes
  2. Producer: The producer is the sender of the message, which sends the message to the RabbitMQ exchange (Exchange)
  3. Exchange: The exchange receives messages sent from producers and routes the messages to one or more queues according to specific rules.
  4. Queue: The queue is the receiver of messages, which stores messages to be processed. Consumers can get messages from the queue and process them
  5. Consumer Consumer: The consumer is the receiver of the message. It obtains the message from the queue and processes it.

Figure 262 for Node.js

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

Figure 263 for Node.js

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.

Figure 264 for Node.js

There are four modes of publish and subscribe

  1. Direct mode: Put the message into the queue designated by the switch key.
  2. 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.
  3. Headers mode: put the message into the switch header attribute to match the queue
  4. 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

js
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

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

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

js
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)

js
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)

js
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)

js
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)

js
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)

js
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:

  1. Direct exchange: forwards messages directly to a specific queue based on the routing key of the message.
  2. Topic exchange: performs fuzzy matching based on the routing key of the message and forwards the message to the queue that meets the conditions.
  3. Headers exchange: Forward based on the header information of the message.
  4. Broadcast switch (fanout exchange): broadcast the message to all queues under the switch

Effect demonstration

Figure 265 for Node.js

View original text


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…

Figure 266 for Node.js

Installation

Drag the downloaded file into the plugins directory under your rabbitMQ

sh
#举例
D:\Applaaction\rabbitmq_server-3.13.0\plugins

Figure 267 for Node.js

Enable plugin

Execute the following command

sh
rabbitmq-plugins enable rabbitmq_delayed_message_exchange

8dc833547ba5ba97fb0b49f974f8751.png

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

Figure 268 for Node.js

Code writing

Application scenarios

7cc8b35ef4cc51706924b867b68865f.jpg

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.

  1. Let’s use the new delay type to switch the type x-delayed-message
  2. When connecting to the switch, add Objects and add x-delayed-type. The target switch type uses direct here.
  3. Add header information x-delay: time delay (ms) when publishing a message
js
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

js
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

Figure 269 for Node.js

View original text


Nodejs Chapter 78 (Kafka)

Figure 270 for Node.js

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

{6F19353C-2331-497e-8A81-11EF280E761C}-fotor-2024061111149.png

  1. Producer: Producer, the producer of messages, is the entrance to messages
  2. 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.
  3. 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.
  4. 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.
  5. Message: The body of each message sent.
  6. Consumer: The consumer, the consumer of the message, is the outlet of the message.
  7. 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!
  8. 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…

Figure 271 for Node.js

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.

Figure 272 for Node.js

Test whether the installation is successful

sh
java --version

Figure 273 for Node.js

Install ZooKeeper

Because Kafka also uses ZooKeeper

ZooKeeper official website zookeeper.apache.org/releases.ht…

Figure 274 for Node.js Figure 275 for Node.js

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

Figure 276 for Node.js

Install Kafka

Kafka official website kafka.apache.org/

Figure 277 for Node.js

  1. Unzip the downloaded file into a directory of your choice
  2. 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)
  3. Open the kafka/config/server.properties file and modify log.dirs to log.dirs=./logs
  4. Start kafka and execute the following command in the kafka root directory
sh
.\bin\windows\kafka-server-start.bat .\config\server.properties

Figure 278 for Node.js

Nodejs writes basic use cases to test kafka

Install dependencies kafkajs official website kafka.js.org/docs/gettin…

sh
npm i kafkajs

Producer (i.e. sender)

js
// 导入所需的模块
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)

js
// 导入所需的模块
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

Figure 279 for Node.js

View original text


Nodejs Chapter 79 (Kafka Advanced)

Figure 280 for Node.js

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.

py
#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.

py
#配置生产者的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

py
#定义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

js
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.

js
await producer.send({
  topic: "xiaoman",
  messages: [
    {
      value: "测试数据1",
      headers: {
        name: Buffer.from("小满"),
      },
    },
    { value: Buffer.from("测试数据2") },
  ],
})

Consumers obtain headers metadata

js
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.

js
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.

  1. Process item by item
  2. Batch processing (batch processing can reduce network overhead)
js
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

Figure 281 for Node.js

View original text


Nodejs Chapter 80 (Kafka Advanced)

Figure 282 for Node.js

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

Figure 283 for Node.js

Modify the configuration file kafka2/config/server.properties this file

js
broker.id=1 //唯一broker
port=9093 //切换端口
listeners=PLAINTEXT://:9093 //切换监听源

Start zooKeeper and kafka and kafka2

sh
.\bin\windows\kafka-server-start.bat .\config\server.properties

Figure 284 for Node.js

2. Client management

View cluster information and client objects

js
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.

js
{
  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.

js
//创建主题
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

js
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()

View original text


Nodejs Chapter 81 (Nacos Registration Center)

Figure 285 for Node.js

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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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

nacos.io/download/na…

Figure 286 for Node.js

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

js
//把注释打开默认是注释掉的 大概在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

Figure 287 for Node.js

3. Import nacos database file and register the database

sql
CREATE DATABASE `nacos`
    DEFAULT CHARACTER SET = 'utf8mb4';

Figure 288 for Node.js

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

Figure 289 for Node.js Figure 290 for Node.js

4. Write startup command

Just put it on the desktop

bat
cd D:\Applaaction\nacos\bin
./startup.cmd -m standalone

5. Install java environment

Official website www.oracle.com/java/techno…

Figure 291 for Node.js

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

Figure 292 for Node.js

7. Access nacos client

Figure 293 for Node.js

Code Case Nodejs

sh
npm install nacos

Server registration + health check

Post.js simply creates a service port 8080

js
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

js
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

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, // 健康检查超时时间
  },
})

Figure 294 for Node.js

View original text


Nodejs Chapter 82 (Nacos dynamic configuration)

Figure 295 for Node.js

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

Figure 296 for Node.js

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.

Figure 297 for Node.js

Case Demonstration

Add, delete, modify and check configuration items visual version

Figure 298 for Node.js

  1. Data ID is a key
  2. Group grouping
  3. Configuration format is the data format you want to store.
  4. Configuration content and stored data

Figure 299 for Node.js

Add, delete, modify and check configuration items code version

  1. New configuration item for publishSingle
  2. remove Delete configuration items
  3. getConfig reads configuration items
  4. subscribe to monitor changes in configuration items
js
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")
})

View original text


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.

Figure 300 for Node.js

Scene

  1. Application Log Analysis: Analyze application logs in real time to quickly discover and solve problems.
  2. Website Search: Provides fast full-text search function for websites to improve user experience
  3. Map Service: Provide location-based search and navigation services

Installation

1. Install elastic

Download address www.elastic.co/cn/download…

Figure 301 for Node.js

  1. Select the operating system you have and download it
  2. 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

  1. Start and run the elasticsearch file under the bin directory
  2. Modify the elastic password and execute elasticsearch-reset-password -u elastic -i under the bin directory and then enter the password, for example 123456
  3. Close https and open elasticSearch/config/elasticsearch.yml and change it to false

Figure 302 for Node.js

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

Figure 303 for Node.js

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

Figure 304 for Node.js

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

Figure 305 for Node.js

Kibana is developed based on the Nodejs environment, and Nodejs needs to be installed. If you have already installed it, ignore it.

  1. After downloading, unzip it to your favorite directory (just wait if the decompression is slow)
  2. After decompression is complete, run the kibana/bin/kibana.bat file.
  3. After opening, visit http://localhost:5601/

80d50c3610ee8501e424409c391852c.png

Add test data

a12f09ea680a459ab388561753b5cfa.png

Access test data

Figure 306 for Node.js

Connect to Node.js

Install dependency packages

sh
npm install @elastic/elasticsearch

Implementation of additions, deletions and modifications

core concepts

  1. 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 database in the database.
  2. 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.
js
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

sh

# 创建索引
PUT /task-index

# 添加文档到索引
POST /task-index/_doc
{
    "id": "1",
    "title": "不是哥们",
    "description": "杰哥不要啊杰哥??????????、啊"
}

# 搜索信息 q就是query的简写
GET /task-index/_search?q="杰哥"

Figure 307 for Node.js

View original text


Figure 308 for Node.js

The basic usage of ElasticSearch has been introduced in the previous chapter. I won’t elaborate too much here.

Simulate fake data

  1. Install the library @faker-js/faker, a library that simulates fake data and is very easy to use and supports Chinese.
  2. Use Chinese locale: [zh_CN], just set it
  3. Generate name, email, mobile phone number, ID, age, gender
  4. After the generation is completed, use fs to write the data.json file
js
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

json
 [{
    "name": "隐强",
    "email": "k7nggq88@126.com",
    "phone": "79533230542",
    "id": "945e80bb-9ece-428b-925c-1ed01e26d660",
    "age": 44,
    "isMale": true
  },
   ......]

Node.js integrates ElasticSearch

  1. fs reads the file just written
  2. Install the ElasticSearch package @elastic/elasticsearc
  3. 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.
  4. Check whether this index Error if created repeatedly has been created before
  5. If this index has not been created, create it and build the mapping table, which is the field properties
  6. Batch insert data encapsulates a function bulkInsert
  7. Implement the inserted function bulkInsert
  8. Search
js
//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.

js
const response = await client.search({
  index: "users",
  query: {
    match_all: {}, //空对象即可
  },
  size: 100, //返回100条
})

Figure 309 for Node.js

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.

js
const response = await client.search({
  index: "users",
  query: {
    match: {
      name: "隐强",
    },
  },
  size: 100,
})
console.log(response.hits.hits)

Figure 310 for Node.js

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

js
const response = await client.search({
  index: "users",
  query: {
    term: {
      "name.keyword": "隐强",
    },
  },
  size: 100,
})
console.log(response.hits.hits)

Figure 311 for Node.js

4. Combined query

  1. Must must match the condition. It matches here (implicitly strong)
  2. Filter condition filtering matches age (people aged 20-60)
  3. must_not must not match (here it means that the returned value cannot contain people with Chinese characters)
  4. should optional condition (implicitly matched here)
js
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)

Figure 312 for Node.js

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.

js
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.

json
[
  { "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 }
]

View original text


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.

Figure 313 for Node.js

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

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

Figure 314 for Node.js

Comparison between cluster operation and non-cluster operation

Write a non-cluster service, index2.js runs non-cluster

js
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

sh
npm install -g loadtest

execute command

sh
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

Figure 315 for Node.js

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.

View original text


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.

Figure 316 for Node.js

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

sh
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.

js
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.
sh
pm2 start app.js xx.js bb.js ......
2. View the currently running node process
sh
pm2 list

Figure 317 for Node.js

3. Stop a node process
sh
pm2 stop [process_id]

Figure 318 for Node.js

4. Restart the service
sh
pm2 restart [process_id]
5. Delete service
sh
pm2 delete [process_id]
6. Start automatically after booting

linux

  1. First run a script such as pm2 start app.js
  2. Save process information pm2 save
  3. Generate startup script pm2 startup
  4. Boot auto-start command pm2 startup systemd
  5. Save the self-start command pm2 save
  6. Delete automatic startup pm2 unstartup systemd
  7. Save, delete and start pm2 save

windows

  1. Install windows automatic startup package npm install pm2-windows-startup -g
  2. Install the self-starting script pm2-startup install
  3. Start service pm2 start xxxx
  4. Save the self-starting service pm2 save
  5. Delete automatic startup pm2-startup uninstall

3. Log

Various log feedback can be collected to debug issues

sh
pm2 log

Figure 319 for Node.js

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.

sh
pm2 monit

Figure 320 for Node.js

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.

sh
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.

Figure 321 for Node.js

6. Configuration file

Call the following command to generate the configuration file ecosystem.config.js in the project or create it manually

sh
pm2 init simple

ecosystem.config.js

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

sh
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

Figure 322 for Node.js

View original text