01. Node. Js
Node.js is a JavaScript runtime environment based on the Chrome V8 engine
Installation and operation
Nodejs.org/zh-cn/downl…
Create a project
mkdir node
cd node
npm init -y
Copy the code
Create a new index.js file
All this code does is output the contents of the package.json file.
Version management
How to Switch Node.js versions on the same device Version management tool:
- N: an NPM global open source package, is a dependency
npm
To global installation, use - FNM: Fast, simple and compatible
.node-version
和.nvmrc
file - NVM: standalone package,
Node Version Manager
The characteristics of
Asynchronous I/O, single thread, cross-platform
Asynchronous I/O
When Node.js performs an I/O operation, the response returns and the operation resumes, rather than blocking the thread and wasting CPU loops waiting.
When Node.js performs an I/O operation, the response returns and the operation resumes, rather than blocking the thread and wasting CPU loops waiting
* The order in which code is written has nothing to do with the order in which it is executed
const { readFile } = require('fs');
readFile('./package.json', { encoding: 'utf-8' }, (err, data) => {
if (err) {
throw err;
}
console.log(data);
});
console.log(123456);
Copy the code
Single thread
Node.js preserves the single-threaded nature of JavaScript in the browser
Advantages:
- You don’t have to worry about state synchronization everywhere, deadlocks don’t happen
- There is no performance overhead associated with thread context switching
Disadvantages:
- Unable to utilize multi-core CPUS
- Errors can cause the entire application to quit, resulting in poor robustness
- A large number of calculations occupy the CPU and cannot be performed
Take the browser as an example. The browser is multi-process and the JS engine is single-thread
Browser process: The main Browser process, only one
Plug-in process: Created when the plug-in is used
GPU process: at most one is used for 3D drawing
Rendering process: page rendering, JS execution, event processing
- GUI rendering thread +
JS engine thread + V8
- Event trigger thread
- Timer trigger thread
- An asynchronous request
cross-platform
Compatible with Windows and Linux platforms, mainly due to the construction of a layer of platform architecture between the operating system and Node upper module system.
Application scenarios
Node.js has its place in most areas, especially I/O intensive ones
- Web applications: Express/Koa
- Front-end build: Webpack
- GUI client software: VSCode/netease Cloud Music
- Others: real-time communication, crawler, CLI, etc
02. Modularity mechanism
1. What is modularity?
To break a large program into smaller interdependent files based on function or business and then assemble them in a simple way
2. Why modular? No modularity problem
- All script tags must be in the correct order, otherwise they will rely on errors
- Global variables have name conflicts and cannot be reclaimed
- IIFE/namespace can cause a lot of problems with code readability
Common. JS specification
Node.js supports the CommonJS module specification and loads modules synchronously
Loading mode:
- Load the built-in module require(‘fs’)
- Load relative | absolute path to the file module
-
require('/User/... /file.js')Copy the code
-
require('./file.js') Copy the code
- Load NPM package require(‘lodash’)
NPM: require(‘lodash’)
- Current directory node_modules
- If not, ndoe_modules of the parent directory
- If not, recurse up the path to node_modules in the root directory
- If package.json.main is not found, the file will be loaded. If package.json is not found, the file will be searched for index.js, index.json, and index.node in sequence
Require. The cache contains loaded modules. The reason for the cache is synchronous loading
- File module search time, if every require needs to search again, the performance will be more check;
- In real development, modules may contain side effect code
Other modular specifications
- AMD is RequireJS in the promotion process of standardized output, asynchronous loading, advocate dependency preloading;
- CMD is the standardized output of SeaJS in the promotion process, asynchronous loading, advocating the nearest dependence;
- The UMD specification is compatible with AMD and CommonJS schemas
- ES Modules(ESM), a language-level modularity specification that is context-independent and compiled with Babel
ES Modules(ESM)
ESM is a modular standard proposed in ES6 language level. The ESM contains two keywords: import and export. Console. log cannot print two keywords.
CommonJS VS ESM
- The CommonJS module prints a copy of the value; The ESM module outputs references to values
- CommonJS modules are loaded at runtime; ESM modules are compile-time output (pre-loaded)
Can mix, but it is not recommended (import commonjs | | the require of imprt)
2.6 Common Modules
03. Package management
Introduce NPM
NPM is package management in Node.js and provides install, delete, and other commands to manage packages
Private NPM
- Mirror company internal private NPM
- NPM config set registry=bnpm.byted.org
other
- The parallel installation
- Flat management
- Lockfile
- Cache optimization
- NPM | yarn = > lock/flat/cache
- PNPM => Monorepo/hard, symbolic link/high security…
04. Asynchronous programming
Callback
Promise
Promise is a finite state machine with four states, three of which are Pending, Fulfilled, Rejected and one state that has not started.
Using Promise, the implementation reads the file contents corresponding to the main field in package.json.
Promise solved the problem of callback hell.
Event
Publish subscribe mode, Node.js built-in Events module, such as HTTP Server on(‘request’) event listener
05. Web application development
The HTTP module
Build the simplest HTTP service? Node.js has a built-in HTTP module
const http = require('http'); http.createServer((req,res)=>{ res.end('Hello World\n'); }), listen (3000, () = > {the console. The log (' App running at http://127.0.0.1:3000/ ')})Copy the code
Koa is introduced
Koa – Koa, the next generation Web development framework based on the Node.js platform, not only provides a lightweight and elegant library of functions that makes it easy to write Web applications without binding any middleware to the kernel methods
const app = new Koa(); app.use(async ctx => { ctx.body = 'Hello World'; }); app.listen(3000,() =>{ console.log('App start at http://localost:3000 ... '); })Copy the code
Koa middleware
A Koa application is an object containing a set of middleware functions that are organized and executed according to the Onion model
Koa-based front-end framework
Open source: ThinkJS/Egg… Internal: Turbo, Era, Gulu… What did they do?
- Koa object response/Request/Context/Application extension
- Koa common intermediate library
- Company internal service support
- Process management
- The scaffold
- .
06. Development and debugging
Log debugging – Breakpoint debugging
npm install ndb -g
Copy the code
ndb node bootstrap.js
07. Online deployment
Utilize multi-core cpus
The process to protect
Node.js process management tool:
- Multiple processes
- Automatic restart
- Load balancing
- The log view
- Performance monitoring
- .