Node series: 2. Modularization

Time:2021-5-4

Node series: 2. Modularization

1、 Write on the front

In order to unify the implementation of JavaScript outside the browser, commonjs was born. Commonjs tries to define a set of APIs used by common applications, so as to fill the shortage of JavaScript standard library which is too simple. Commonjs specification includes module, package, system, console, file system, unit test and so on.

Node.js is the most popular implementation of the common JS specification. With the update of the common JS specification, node.js is also following up, but node.js does not fully follow the common JS specification. This is an embarrassing situation for all the specification makers, because the specification always lags behind the development of technology.

2、 Modularization of node

Module and package are the most important pillars of node.js. It is impossible to develop a program with a certain scale with only one file. It is usually necessary to split, encapsulate and then combine various functions. Module was born to realize this way.

In browser JavaScript, the split and combination of script modules are usually implemented with HTML script tags. Node.js provides the require function to call other modules, and the modules are based on files. In other words, each file is a module, and the mechanism is very simple.

Module type

Nodejs module can be divided into two categories, one is the core module, the other is the file module.

Core moduleIt is provided by nodejs. When the node process starts, some core modules are directly loaded into memory, so we can directly import these core modules through require. Such as HTTP module, URL module, FS module and so on.

const http = require('http'); //  Built in module direct reference
const host = '127.0.0.1';
const port = 3000;

const server = http.createServer((req,res) => {
    res.statusCode = 200;
    res.end('test1');
})

server.listen(port, host, () => {
    Console.log (` server running at http: // ${host}: ${port} / ')
})

File moduleDynamic loading at run time requires complete path analysis, file location, compilation and execution process, which is slightly slower than the core module, but uses a lot. There are two ways to load the file module, one is to load by path, the other is to searchnode_modulesfolder.

Load mode by path

// custom_ Tools file in the module folder
function calculate(num) {
   return num*2
}
function getUrl(domain) {
    return `${domain}/wanwan0306`
}
module.exports = {
    calculate,
    getUrl
}

// app.js
const http = require('http');
const { calculate, getUrl } = require('./custom_ module/tools');  //  Introduce by path
const host = '127.0.0.1';
const port = 3100;

const server = http.createServer((req,res) => {
    const num = calculate(20);
    const url = getUrl('https');
    res.statusCode = 200;
    res.end(`${num}-${url}-test2`);
})

server.listen(port, host, () => {
    Console.log (` server running at http: // ${host}: ${port} / ')
})

node_ Modules folder loading mode

// node_ Tools file in modules folder
function calculate(num) {
   return num*2
}
function getUrl(domain) {
    return `${domain}/wanwan0306`
}
module.exports = {
    calculate,
    getUrl
}

// app.js
const http = require('http');
const { calculate, getUrl } = require('tools');  // node_modules
const host = '127.0.0.1';
const port = 3200;

const server = http.createServer((req,res) => {
    const num = calculate(20);
    const url = getUrl('https');
    res.statusCode = 200;
    res.end(`${num}-${url}-test3`);
})

server.listen(port, host, () => {
    Console.log (` server running at http: // ${host}: ${port} / ')
})

Loading rules

1. If the require parameter string starts with ‘/’, it means that a module file in the absolute path is loaded. For example,Requirement ('/ future / demo / nodejs / 2_ module/tools.js')Will load/Future / demo / nodejs / 2. Modularization / custom_ module/tools.js

2. If the require parameter starts with “.” / “or” / “, the module is searched by relative path, which is the most common way in application. For example, in the previous example, we usedrequire('./custom_module/tools')To load;

3. If the require parameter does not start with “.” / “or” / “, and the module is not a core module, you need to find thenode_modulesTo load the module (the package obtained by NPM is usually loaded in this way);

For example: scripts/Future / demo / nodejs / 2. Modularization / app3.jsImplementedrequire('tools.js')Command, node searches for the following files in turn.

/usr/local/lib/node/tools.js
/Future / demo / nodejs / 2. Modularization / node_ modules/tools.js
/future/Demo/NodeJs/node_modules/tools.js
/future/node_modules/tools.js
/node_modules/tools.js

4. If the specified module file has no suffix, node will try to add a suffix to the file name.js、.json、.nodeAfter that, search again JS file will be parsed with JavaScript script file in text format,. JSON file will be parsed with text file in JSON format,. Node file will be parsed with compiled binary file;

be careful:The core module has the highest loading priority. In other words, node.js will always load the core module if there is a module name conflict.

Load cache

The node.js module will not be loaded repeatedly. This is because node.js caches all the loaded file modules through the file name, so it will not be loaded again when it is accessed in the future,Note that node.js is cached based on the actual file name, not the parameters provided by require(),That is to say, even if you pass therequire('tools')andrequire('./node_modules/tools')Load twice, and it will not be loaded repeatedly, because although the two parameters are different, the parsed file is the same.

Package manager: NPM

NPM websitehttps://www.npmjs.cn/

NPM is a package management tool installed with nodejs, which can solve many problems in nodejs code deployment. The common use scenarios are as follows:

  1. Users are allowed to download third-party packages written by others from NPM server for local use.
  2. Users are allowed to download and install command-line programs written by others from NPM server for local use.
  3. Users are allowed to upload their own packages or command-line programs to NPM server for others to use.

Use the NPM command to install the module. The syntax is as follows

NPM install express // local installation
NPM install Express - g // global install

Local installation

  1. Place the installation package in the./node_modules If you do not have thenode_modulesDirectory, which will be generated under the directory where the NPM command is currently executednode_modulescatalog.
  2. Locally installed packages can be introduced through require().

Global installation

  1. Place the installation package in the /usr/local Or younodeThe installation directory of.
  2. It can be used directly on the command line.

Package.json is used to define the properties of a package. Next, let’s create the following:

$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
Package name: (2. Modularization) test // module name
version: (1.0.0) 
Description: nodejs modular demo // project description
entry point: (app1.js) 
test command: 
git repository: 
keywords: 
author: wanwan
license: (ISC) 
About to write to /xx/package.json:

{
  "name": "test",
  "version": "1.0.0",
  "Description": "nodejs modular demo,",
  "main": "app1.js",
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "wanwan",
  "license": "ISC"
}


Is this OK? (yes) yes

NPM common instructions

NPM version view module version
NPM help view detailed help for a command
NPM install module
NPM uninstall module
NPM update module
NPM outdated checks if the module is obsolete
NPM LS view installed modules
NPM init creates a package. JSON file in the project

4、 References

  1. Nodejs development guide.pdf
  2. Node learning guide.pdf
  3. Commonjs specification — JavaScript standard reference tutorial (alpha)

Complete sample code:https://github.com/wanwan0306/future/tree/master/Demo/NodeJs/2. modularization

Recommended Today

Large scale distributed storage system: Principle Analysis and architecture practice.pdf

Focus on “Java back end technology stack” Reply to “interview” for full interview information Distributed storage system, which stores data in multiple independent devices. Traditional network storage system uses centralized storage server to store all data. Storage server becomes the bottleneck of system performance and the focus of reliability and security, which can not meet […]