Related articles

  • P01: Node.js tutorial from a practical perspective
  • P02: Basic node usage
  • P03: Node built-in module PATH
  • P04: Buffer for nodeAPI
  • P05: Events of node built-in module
  • P06: Node built-in module FS (1)
  • P07: Node built-in module FS (2)
  • P08: Node implements static server ~ create project
  • P09: Node implements static server ~ Hello HTTP
  • P10: Node implements static server ~ static file or folder reading

Module Common usage and precautions

  • Module wrapper
    • Before executing the module code, Node.js wraps it with a function wrapper
      (function(exports, require, module, __filename, __dirname) {
          connsole.log('The code for the module is actually here')});Copy the code
  • How do I create a module
    • Creating a file => implements private scope
      // The file name is 02_mymodule.jsCopy the code
    • Write some operations, logic, numbers, etc
      // Define a variablelet testVar = 'test'// Define a functionfunction test() {
              console.log(testVar)
          }
          
      Copy the code
    • Foreign thrown
      Module.exports = // exports.testVar = module.exportstestVar
          module.exports.testFn = test
      Copy the code
    • The complete code
      // Define a variablelet testVar = 'test'// Define a functionfunction test() {
              console.log(testVar)} // Expose module.exports.testvar =testVar
          module.exports.testFn = test
      Copy the code
  • How to reference a module
    • / absolute path,./.. / Relative path
      • Support js, JSON,node extension, do not write the extension to try, do not save the error
      const myMo = require('./02_myModule')
      Copy the code
      • If the path is not written, it is considered a build-in module or a third party module in each node_modules level
      const VUE = require('vue')
      Copy the code
    • The way a built-in module is referenced
      Const fs = require(const fs = require('fs')
      
      const result = fs.readFile('./07_fs.js', (err, data) => {
          if(err) {
              console.log(err)
          } else{console.log(data) // say hexadecimal escape string console.log(data.tostring ())}}) // Use undefined console.log(result)Copy the code
    • Referencing external modules
       const myMo = require('./02_myModule')
      Copy the code
    • Reference the file named 02_mymodule.js and use it
      // support javascript,json,node extension const myMo = require('./02_myModule')
          console.log(myMo.testVar)
          myMo.testFn()
      Copy the code

Require particular attention to

  • Module is executed when it is loaded and cached after loading
  • Once the module is cyclic loaded, only the executed part will be output, and the unexecuted part will not be output.
  • 04_moduleA.js
        module.exports.test = 'A'
        
        const modB = require('./05_moduleB')
        
        console.log('what modA:'+ modb. test) // Define module.exports.test = again'AA'
    Copy the code
  • 05_moduleB.js
        module.exports.test = 'B'
        
        const modA = require('./04_moduleA')
        
        console.log('modB:'// define module.exports.test = again'BB'
    Copy the code
  • 06_main.js
        const modA = require('./04_moduleA'//1 references 04_moduleA //2 internal references 05_moduleB //3 05_moduleB internal references 04_moduleA, when module.exports.test = A in 04_moduleA. So print modB for the first time: A // will module.exports.test ='BB'//4 => so print modA: BB for the second time and reset module.exports.test ='AA'
        const modB = require('./05_moduleB') //5 Directly reads cache console.log(moda.test) //6 Prints AA console.log(modb.test) for the third time //7 Prints BB for the fourth timeCopy the code
    ModB: A modA: BB AA BBCopy the code

Module pay special attention to

  • Exports and Module. exports
    • Exports is short for module.exports
      // exports = module. Exports = {a:1} // exports = {a:1} // undefined Module. exports = {a: 1} // Exports = {a: 1}Copy the code

global

  • Global top-level object
    • Analogous to Windows in JS
    • CommonJS
    • Common methods such as Buffer Process Console => their lower mounting methods
    • Timer => A series of scheduled operations
    • specific
      • Declared objects can be local or global. Objects declared using global.XXX are global objects, which are directly mounted under the global
      //09_global file // Declare local variable consttestVar = 100 // Declare the global variable global.testvar2 = 1000 module.exports. TestVar =testVar
      Copy the code
      Const mod = require(const mod = require('./09_global')
      console.log(mod.testVar)
      console.log(testVar2) // Can be used without exporting or referencingCopy the code

process

  • Process Global Mounted process
    • Common parameters of process
      Argv => The process starts with an array of arguments. 1. Nodexx.js a=1 b=2 then the corresponding argument is stored in argv array otherwise argv0 => first argument of argv arrayexecArgv => node --inspect xxx.js the parameter that precedes the file name, that is, the startup configuration parameter for nodeexecPath => node Path where the script is invoked, that is, the node startup PathCopy the code
    • The process environment
      Const {env} = process console.log(env) // Saves the configuration of the startup environment {ALLUSERSPROFILE:'C:\\ProgramData'. . . USERNAME:'Administrator',
            USERPROFILE: 'C:\\Users\\Administrator',
            windir: 'C:\\Windows',
            windows_tracing_flags: '3',
            windows_tracing_logfile: 'C:\\BVTBin\\Tests\\installpackage\\csilogfile.log',
            TERM_PROGRAM: 'vscode',
            TERM_PROGRAM_VERSION: '1.36.1',
            LANG: 'zh_CN.UTF-8' }
      Copy the code
    • Process CWD => Note that this is a direct method of process
      Console. log(process.cwd()) // Path of the current process F:\ XXX \node_xxx\demoCopy the code
    • process timer
      // Next team to line up firstsetImmediate(() => {
              console.log('setImmediate'}) // Execution between these two is also directly under GlobalsetTimeout(() => {
              console.log('setTimeout'}, 0) process.nexttick (() => {console.log();'nextTick')})Copy the code

close