Basics of Node.js
Introduction to the
Node.js is a cross-platform JavaScript runtime environment based on the Google V8 engine
- Website nodejs.org/en/
The characteristics of
- Asynchronous I/O
- Single thread
- cross-platform
asynchronousI/O
When Node.js performs an I/O operation, it will resume the operation when the response comes back, 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
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 an entire application to quit, resulting in poor robustness
- A large number of calculations occupy the CPU, causing execution to fail
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
Modular mechanism –
Modularity: Breaking up a large program into smaller interdependent files based on function or business and stitching them together in a simple way
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
CommonJS VS EMS
// CommonJS module Demo 1 2
//demo1.js
const prefix = 'hello';
const sayHi = (() = > {
return prefix + ' world'
})
module.exports = {
sayHi,
}
//demo2.js
const sayHi = require('./demo1.js');
console.log(sayHi.sayHi()) //hello world
// ES Modules demo 3 4
//demo3.mjs
const prefix = 'hello';
export const sayHi = (() = > {
return prefix + ' world'
})
//demo4.mjs
import { sayHi } from './demo3.mjs';
console.log(sayHi()) //hello world
Copy the code
- The CommonJS module prints a copy of the value; The EMS module outputs references to values
- CommonJS modules are loaded at runtime; EMS module is compile-time output (pre-loaded)
Package management mechanismNPM
NPM -v You can view the NPM version
Common commands
- NPM init — initialization to automatically generate package.json
- NPM config — Gets configuration items
- NPM run — Run
- NPM install — Install
- NPM uninstall — Uninstall
- NPM update — Updates
- NPM info — View package information
- NPM publish — publish
Asynchronous programming
Callback
- Read the file contents corresponding to the main field in package.json
Promise
- Promise is an effective state machine with four states, including three core states: Pending, Fulfilled, Rejected and one unstarted state.
await
- The await function uses try catch to catch exceptions
Event
- Publish subscribe mode, Node.js built-in Events module