nodejs -- modularization, module scope, several methods of exporting data, package, package management, custom package, module loading mechanism

Keywords: node.js Front-end

1, First knowledge modularization

Modularization is the process of dividing the system into several modules from top to bottom when solving a complex problem. For the whole system, modularization is a unit that can be combined, disassembled and replaced.

Modularization in the field of programming is to abide by the inherent rules and divide a large file into independent and interdependent small modules

1.1 benefits of modular splitting

It improves the reusability of the code

Improved code maintainability

On demand loading can be realized

  1.2 modules in browser development

  • In order to avoid naming conflicts in browser development,   Easy maintenance, etc
  • We use classes or immediately execute functions to encapsulate JS code,   To avoid naming conflicts and improve code maintainability
  • In fact, a class or an immediate execution function here is a module in browser development
  let obj = {

       Business logic code in module

   };

   ;(function(){

      Business logic code in module

      window.xxx = xxx;

   })();

Existing problems: no standards, no specifications

1.3 modular specification

Modular specification refers to the rules to be observed when the code is divided and combined in a modular way

For example:

  • What syntax format is used to reference modules
  • What syntax and format are used in the module to expose members
  • ......

Benefits of modular specification: we all follow the same modular specification to write code, which reduces the cost of communication and greatly facilitates the mutual call between various modules for the benefit of others and ourselves

1.4 modules in nodejs development

In nodejs, modules are divided into three categories according to different sources:

  • Built in module (the built-in module is officially provided by nodejs, such as fs, path, http, etc.)
  • Custom module (each. js file created by the user is a custom module)
  • Third party module (the module developed by the third party is not an official built-in module or a user-defined module, which needs to be downloaded before use)

NodeJS implements the module system using the CommonJS specification

The CommonJS specification specifies how to define a module,   How to expose (export) variable functions in the module,   And how to use the defined modules

  • -   In the CommonJS specification, a file is a module
  • -   In the CommonJS specification, the variable functions in each file are private and invisible to other files
  • -   In the CommonJS specification, the variable functions in each file must be exposed (exported) through exports before other files can be used
  • -   In the CommonJS specification, variable functions exposed by other files must be imported into the module through require() before they can be used

How to load modules:

Using the powerful require() method, you can load the required built-in modules, user-defined modules and third-party modules for use, such as:

// 1. Load the built-in fs module
const fs = require('fs');

//2. Load custom module
const custom = require('./cuustom.js');

//3. Load the third-party module
const moment = require('moment');

Example:

 a.js,

let name = "jack";

function sum(a, b) {
    return a + b;
}

exports.str = name;
exports.fn = sum;

b.js,

let aModule = require("./06-a");
console.log(aModule);
console.log(aModule.str);
let res = aModule.fn(10, 20);
console.log(res);

1.5 precautions for using require

require when importing a module, you can not add the type of the imported module:

For example: (let)   aModule  =  require("./09");)

If the type of import module is not specified,   Then. js will be found in turn  . json  . node file

Whichever of the three types,   After importing, it will be converted into JS objects and returned to us

You must specify a path when importing custom modules:

require can import custom module (file module), system module (core module) and third-party module

The path (let) must be preceded when importing the custom module module   aModule  =  require("./09-a.js");)

There is no need to add a path to import "system module" and "third-party module"

The reason why you do not need to add a path is to import "system module" and "third-party module":

If it is a "system module", go directly to the path of environment variable configuration

If it is a "third-party module", it will be searched in sequence according to the path in the module.paths array

Two. Module scope

2.1 what is module scope

Similar to the function scope, variables, methods and other members defined in the user-defined module can only be accessed in the current module. This module level access mechanism is the module scope

2.2 advantages of using module scope

The problem of global variable pollution is prevented

 

3, Several ways of exporting data from node module

3.1 module.exports object  

In each. js custom module, there is a module object that stores information related to the current module

In the user-defined module, you can use the module.exports object to share the members in the module for external use

When the user-defined module is imported by the outside world with require(), the object pointed to by module.exports is obtained

Syntax: module.exports.xx  =  yy

a.js,

let name = "iwen";

function sum(a, b) {
    return a + b;
}


//Mode 1: module.exports.xx = YY
// module.exports.str = name;
// module.exports.fn = sum;
//or
module.exports = {
    str: name,
    fn: sum
};

 

b.js,

let aModule = require("./07-a");

console.log(aModule);
console.log(aModule.str);
console.log(aModule.fn(10, 20));

// let res = aModule.fn(10, 20);
// console.log(res);

 

3.2 exports object

Because the word module.exports is complex to write, node provides the exports object to simplify the code of sharing members externally.

By default, exports and module.exports point to the same object, and the final shared result is module.exports   The object pointed to shall prevail, that is, the object pointed to by module.exports shall always prevail when the require() module is used

Syntax: exports.xx  =  yy

a.js

let name = "iwen";

function sum(a, b) {
    return a + b;
}

//Mode 1 exports.xx = yy
exports.str = name;
exports.fn = sum;

b.js

let aModule = require("./07-a");

console.log(aModule);
console.log(aModule.str);
console.log(aModule.fn(10, 20));

3.3 global objects

Syntax: global.xx  =  yy

a.js

let name = "iwen";

function sum(a, b) {
    return a + b;
}

//Mode 3 global.xx = yy
global.str = name;
global.fn = sum;

b.js

let aModule = require("./07-a");

console.log(str);
let res = fn(10, 20);
console.log(res);

3.4 differences between exports and module.exports

Exports can only be exported through   Export data by means of exports.xxx,   Cannot be assigned directly:

a.js,

let name = "lnj";
// exports.str = name;
// module.exports.str = name;

exports = name;

 

b.js,

let aModule = require("./08-a.js");
console.log(aModule);

 

Module.exports can export data through module.exports.xxx,   You can also assign values directly:

a.js,

let name = "lnj";
// exports.str = name;
// module.exports.str = name;


module.exports = name;

 

b.js,

let aModule = require("./08-a.js");

console.log(aModule);

When the module requires (), the object pointed to by module.exports will always prevail:

 

Note:

In enterprise development, do not directly assign values in either way,   This question will only appear in the interview

IV

Posted by NiGHTFiRE on Wed, 24 Nov 2021 01:51:08 -0800