This is the 20th day of my participation in the August More Text Challenge
Modularization mechanism
CommonJS specification
- Loading way
- Load the built-in module require(‘fs’)
- Load the relative or absolute path of the file module require(‘/User/… ‘)
- Load NPM package require(‘lodash’)
- NPM package lookup principles
- Node_modules folder of the current directory
- If not, recurse up the path to node_modules in the root directory
- Json. If package.json is not available, search 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.
- The file module search is time-consuming. If every require needs to be searched again, the performance will be poor.
- In real development, modules may contain side effect 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 specification, compatible with AMD and CommonJS mode.
- ES Modules, a language-level modularity specification that is context-independent and can be compiled with Babel.
Package management mechanism
NPM is package management in Node.js and provides install, delete, and other commands to manage packages.
- Common commands
npm init
npm config
npm run
npm install
npm uninstall
npm update
npm publish
Copy the code
Asynchronous programming
Promise
Promise is a finite state machine with four states, of which three core states are pending, depressing, Rejected and one state that has not started.
Web Application Development
The HTTP module
To build the simplest HTTP service, you can use the built-in HTTP module of Node.js.
KOA is introduced
Koa is the next generation Web development framework based on node.js platform. Koa only provides a lightweight and elegant function library, which makes it easy to write Web applications without binding any middleware in the kernel method. The following describes the execution process.
- The service start
- Instantiate the application
- Registered middleware
- Create services and listen to ports
- Accept/process the request
- Get the REq/RES object
- Execution middleware
- Output the content set to ctx.body