A brief introduction to Node.js

Node.js is a JavaScript runtime environment based on the Chrome V8 engine

Installation and operation

download

https://nodejs.org/zh-cn/download/
Copy the code

Create a project

mkdir node
cd node
npm init -y
Copy the code

Create a new index.js file

const { readFile } = require('fs')

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

Enter the package.json file

node index.js
Copy the code

Version management

How do I quickly switch node.js versions on the same device?

Version management tools:

  • N: a global NPM open source package, is dependent on NPM to install, use globally
  • FNM: fast and simple, compatible with. Node-version and. NVMRC files
  • NVM: Standalone package, Node Version Manager

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

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 * NIx 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 a niche in most areas, especially I/O intensive ones

  • Web applications: Express/Koa
  • Front-end build: WebpackGUI
  • Client software: VSCode/netease Cloud Music
  • Others: real-time communication, crawler, CLI, etc

Second, modular 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 modularization problems All script tags must be in the correct order; otherwise, errors will be reported. Global variables have naming conflicts and memory usage cannot be reclaimed. IIFE/ Namespace may lead to low code readability and many problems

CommonJS specification

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

// greeting.js
const prefix = 'hello';
const sayHi = function () {
    return prefix + 'world';
}
module.exports = {
    sayHi
}

// index.js
const { sayHi } = require('./greeting');
sayHi();
Copy the code

exports = module.exports = { }

// greeting.js
const prefix = 'hello';
const sayHi = function () {
    return `${prefix}  world`;
}
exports.sayHi = sayHi;

// index.js
const { sayHi } = require('./greeting');
sayHi();
Copy the code

CommonJS exports, require, module, __filename, __dirname variables

function (exports.require.module, __filename, __dirname) {
    const m = 1;
    module.exports.m = m;
}
Copy the code

Loading mode:

  1. Load the built-in module require(‘fs’)
  2. Loading relative | | the require absolute path to the file module (‘/User /… /file.js’) require(‘./file.js’)
  3. Load NPM package require(‘lodash’)

NPM package lookup rules:

require(‘lodash’)

  1. Current directory node_modules
  2. If not, node_modules of the parent directory
  3. If not, recurse up the path to node_modules in the root directory
  4. If package.json 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.cache

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

  1. File module search time, if every require needs to search again, the performance will be poor;
  2. In real development, modules may contain side effect code
/ / a cache
const mod1 = require('./foo');
const mod2 = require('./foo');
console.log(mod1 === mod2);     // true

/ / no cache
function requireUncached(module) {
    delete require.cache[require.resolve(module)];
    return require(module);
}
const mod3 = requireUncached('./foo');
console.log(mod1 === mod3);     // false
Copy the code

Other modular specifications

  • AMD is RequireJS in the promotion process of standardized output, asynchronous loading, advocating dependence on preloading
  • CMD is SeaJS standardized output in the promotion process, asynchronous loading, advocating nearby 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

Introduction to Common Modules

file

var fs = require("fs") // Import the fs module
fs.readFile(filename, [options], callback); // Read the file
fs.writeFile(filename, data, [options], callback); / / write file
fs.appendFile(filename, data, [options], callback); // Write files to append
fs.open(filename, flags, [mode], callback); // Open the file
fs.mkdir(path, [mode], callback); // Create directory:
fs.readdir(path, callback); // Read the directory
fs.exists(path, callback); // Check whether files and directories exist
Copy the code

The Path module

var path = require("path") // Introduce the path module
path.basename(path[, ext]); // Returns the last - part of the path
path.dirname(path); // Returns the directory name of path
path.normalize(path);// Get the canonical path
path.isAbsolute(path); // Check whether the path is absolute
path.relative(form,to); The // method returns a relative path from from to based on the current working directory
path.resolve([...paths]); // Resolve a sequence of paths or path fragments to absolute paths
Copy the code

OS module

var os = require("os") // Import the OS module
os.cpus(); // Returns information for each logical CPU kernel
os.hostname(); // Returns the host name of the operating system
os.platform(); // Returns a string that identifies the operating system platform
os.userInfo([options]); // Returns information about the currently valid user
Copy the code

3. Package management mechanism

Introduce NPM

NPM is the package manager in Node.js that provides install, delete, and other commands to manage packages

Common commands:

  • npm init
  • npm config
  • npm run [cmd]
  • npm install [pkg]
  • npm uninstall [pkg]
  • npm update [pkg]
  • npm info [pkg]
  • npm publish

Package. The json file

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

More package.json configurations

Docs.npmjs.com/cli/v7/conf…

Rely on

  • 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
  • NPM config set registry=bnpm.byted.org

other

  • The parallel installation
  • Flat management
  • Lockfile (lock) files
  • Cache optimization
  • .
  • Npm7 | yarn = > lock/flat/cache…
  • PNPM => Monorepo/hard, symbolic link/high security…

Asynchronous programming

Callback

Question: How to solve the callback hell?

const fs = require('fs')

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

Promise

Promise is a finite state machine with four states, including three core states: 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

const { readFile } = require('fs/promises')

readFile('./package.json', { encoding: 'utf-8' }).then(res= > {
    return JSON.parse(res);
}).then(data= > {
    return readFile(data.main, { encoding: 'utf-8' });
}).then(res= > {
    console.log(res);
})
Copy the code

How do I convert a Callback to a Promise? ugl.promisify

function promisify(fn, receiver) {
    return (. args) = > {
        return new Promise((resolve, reject) = > {
            fn.apply(receiver, [...args, (err, res) = > {
                return err ? reject(err) : resolve(res);
            }]);
        });
    };
}
const readFilePromise = promisify(fs.readFile, fs);
Copy the code

await

Await functions catch exceptions using try catch (note parallelism)

const { readFile } = require('fs/promises')

async() = > {const { main } = JSON.parse(await readFile('./package.json', { encoding: 'utf-8' }));
    const data = await readFile(main, { encoding: 'utf-8' });
    console.log(data);
}
Copy the code

Event

Publish subscribe mode, Node.js built-in Events module

For example, HTTP Server on(‘ Request ‘) event listener

// Publish subscribe mode
const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}const myEmitter = new MyEmitter();
myEmitter.on('event'.() = > {
    console.log('an event occurred! ');
});
myEmitter.emit('event');

// The server listens for the request event
const http = require('http');
const server = http.createServer((req, res) = > {
	res.end('hello')}); server.on('request'.(req, res) = > {
    console.log(req.url);
});
server.listen(3000);
Copy the code

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.() = > {
    console.log('the 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, simply provides a lightweight and elegant library of functions that makes it easy to write Web applications without binding any middleware to kernel methods

const Koa = require('koa');
const app = new Koa();

app.use(async ctx => {
    ctx.body = 'Hello World';
});

app.listen(3000.() = > {
    console.log('the App running at http://127.0.0.1:3000/')});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

Koa middleware

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

Common middleware

  • Koa-router: indicates route resolution
  • Koa-body: Request body parsing
  • Koa-logger: logs are recorded
  • Koa-views: Template rendering
  • Koa2-cors: cross-domain processing
  • Koa-session: session processing
  • He’s more like a koa-helmet
  • .

Koa middleware is varied in quality and needs reasonable selection and efficient combination.

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 middleware library
  • Company internal service support
  • Process management
  • The scaffold