Node.js

1. The Node. Js

Introduction to the Node. Js

Not a language, but a JavaScript runtime environment, similar to the Java JVM

Node.js is a broken-down JavaScript runtime environment based on Google’s V8 engine

Liverpoolfc.tv: Node. Js (nodejs.org)

Versions: There are odd and even versions. The even versions are LTS long-term maintenance versions

Installation and operation

index.js

const { readFile } = require('fs');

readFile('./package.json', { encoding: 'utf-8' }, (err, data) = > {
    if (err) {
        throw err;
    }
    console.log(data);
})
Copy the code

run

node index.js
Copy the code

Version management

Use NVM to manage Node.js

Mac && Linux version

The curl - o - https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bashCopy the code

Windows version coreybutler/NVM – Windows: A node.js version management utility for Windows. Ironically written in Go. (github.com)

// Install the specified version of Node
nvm install 16.62.
// Lists the versions already installed on the system
nvm ls

// Use the specified version of Node
nvm use 16.62.

// Uninstall the specified version
nvm uninstall 16.62.

Copy the code

The characteristics of

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

The order in which the 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, and no deadlocks are sent

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 caused the CPU to fail

Take the browser as an example, the browser is multi-process,JS engine is a single thread

The browser process generally includes the browser process, GPU process, renderer process, and plug-in process.

  • GUI rendering process
  • JS engine process +V8
  • Event trigger thread
  • Timer trigger thread
  • Asynchronous request thread

Breaking platform

Compatible with Windows and * Nix platforms, mainly due to the construction of a platform architecture between the operating system and node.js upper modules.

Application scenarios

Node.js is suitable for I/O intensive applications

  • The Web application:Express/Koa
  • Front-end build:Webpack
  • GUI client software:VScode/ netease Cloud Music
  • Others: real-time communication, crawler, CLI, etc

2. Modularity mechanism

Introduction to Modularity

1. What is modularity?

To break a large program into small interdependent files based on function or business and splice them together 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

CommonJSspecification

Node.js supports the CommonJS module specification and loads modules synchronously

Exports ===module.exports, which points to the same block of references in memory

Loading way

  1. Load the built-in module require(‘fs’)

  2. Load relative | absolute path to the file module

    require('c:\abc\file.js')
    require('.\file.js')
    Copy the code
  3. Load NPM package require(‘lodash’)

NPM: require(‘lodash’)

  1. In the current directorynode_modules
  2. If not, the parent directorynode_modules
  3. If not, recurse up the path to the root directorynode_modules
  4. It will load when it finds itpackage.jsonthemainPoint to the file if notpackage.jsonFiles are searched in turnindex.js.index.json.index.node

Require. The cache contains loaded modules. The reason for the cache is synchronous loading

  1. The file module takes time to find if each timerequireAll need to iterate to find, the performance will be poor;
  2. In real development, modules may contain side effect code
  • 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;
  • UMD (Universal Module Definition) specification, compatible with AMD and CommonJS mode
  • ES Modules (ESM), a language-level modularity specification that is context-independent and compiled with Babel

ESM is a modular standard proposed at the ES6 language level

The ESM contains import and export keywords, but cannot console two keywords

M1. MJS file

<script type="module" src="m1.mjs"></script>
Copy the code

3. Package management mechanism

Introduce NPM

Packages typically include index.js and package.json

NPM is the package manager in Node.js and provides other commands to manage packages such as install, delete, and so on

package.jsonfile

  • The name package name
  • Version version number
  • Main entry file
  • Scripts Execute scripts
  • Dependencies
  • DevDependencies Develops dependencies
  • Repository code hosts the address

More configuration

package.json | npm Docs (npmjs.com)

  • Dependencies Packages required for normal application execution after application publication
  • DevDependencies develops dependencies, only for the development environment
  • PeerDependencies are equally dependent, such as a Webpack plug-in that depends on a particular version of Webpack
  • BundledDependencies Package dependencies (NPM run Pack), which must be declared in devDep or DEP
  • OptionalDependencies Optional Dependency

Private NPM

Mirror company internal private NPM

Image setup

npm config set registry=https://xxxxxxx
Copy the code
  • The parallel installation
  • Flat management
  • Lock file
  • Cache optimization

Common commands

npm init
npm config
npm run [cmd]
npm install [pkg]
npm uninstall [pkg]
npm update [pkg]
npm info [pkg]
npm publish
Copy the code

4. Asynchronous programming

callback

promise

Promise is a finite state machine with four states, three of which are core states

  • pendinghang
  • fulfilledcomplete
  • rejectedRefused to

And an unstarted state

async

The await function uses try catch to catch exceptions

event

Node.js has the events module built in

For example, HTTP serve on(‘request’) event listener

5.Web application development

httpThe module

const http = require('http');

http.createServer((req, res) = > {
    res.end('hello');
}).listen(3000.() = > {
    console.log('Started successfully');
});

Copy the code

Koaintroduce

The next generation Web development framework based on Node.js platform

const app = new Koa();

app.use(async ctx => {
    ctx.body = 'hello';
});
app.listen(3000.() = > {
    console.log('Started successfully');
});
Copy the code

Implementation process

  • The service start
    • Instantiate the application
    • Registered middleware
    • Create services and listen to ports
  • Accept/process the request
    • Gets the request REq, RES object
    • Req -> Request, RES -> Response encapsulation
    • request & response -> context
    • Execution middleware
    • Output the content set to ctx.body

The middleware

A Koa application is an object containing a set of middleware functions that are organized and executed according to the Onion model

6. Development and debugging

Breakpoint debugging

The node - inspect = 0.0.0.0:9229 bootstrap. JsCopy the code

NDB tools

npm install ndb -g

ndb node bootstrap.js
Copy the code

Use vscode for debugging

Online debugging

  • The SDK to report
  • Write to file

7. Online deployment

Node.js is a single-threaded model, but its event-driven, asynchronous, non-blocking mode can be applied to high concurrency scenarios, while avoiding the resource overhead caused by thread creation and context switching between threads.

Utilize multi-core cpus

Node.js provides the cluster/child_process module

Process management tool
  • Multiple processes
  • Automatic restart
  • Load balancing
  • The log view
  • Performance monitoring

nodeman

pm2