NodeJs module system

1. Core Module

Node provides many server-level APIs for js, and most of these APIs are packaged in a named core module. For example: fs core module for file operation, http module constructed by http service, path operation module, os operating system information module, etc. All passed

require('fs');

Use after introduction.

2. Module system
  1. In Node, there are three types of modules

    1. Named core module, for example: fs, path
    2. User-defined module
      1. The relative path introduced must be added ./, cannot be omitted, otherwise an error will be reported
      2. The suffix name can be omitted, and the js file is accessed by default
    3. Third-party module
  2. Scope

    1. There is no global scope in Node, only module scope
    2. The outside can't access the inside
    3. The inside can't access the outside
    4. Closed by default
    5. Communication between modules is achieved through require return values
  3. require()

    1. Role: load the module, in order to execute the code in the module and use its members

    2. Return value: the interface object exported by the load file module

    3. Each file module provides an object: the exports object, which is used to communicate with external modules, and use the external data that needs to be accessed by mounting on the exports object.

    4. exports is an empty object by default

      // a.js
      exports.num = 1;// 导出变量num
      
      // b.js
      var ex = require('./a');// 接收到处接口对象ex
      console.log(ex.num);// 使用对象上挂载的数据
      
    5. Note:

      1. The data mounted on exports can also be used through exports on the loaded module.

Guess you like

Origin blog.csdn.net/chen__cheng/article/details/114370055