Node module export introduces two methods and npm package management

Benefits of modularity

  1. In Node.js, each file is treated as an independent module. The variables and functions defined in the module have independent scopes, because Node.js will use the function wrapper as shown below when executing the module code. encapsulate it

    (function(exports,require,module,__filename,_dirname){<!-- -->
    //Module code actually exists here
    });
    
  2. Moreover, the project is composed of multiple modules, each module is independent, and improves module code reusability, on-demand loading, and independent scope.

CommonJS standard export introduction

  1. However, because the properties and functions in the module are private, if they are used externally, they need to use standard syntax to export and import. This standard is called the CommonJS standard. Next, we will experience the modular export and import syntax in a requirement. usage of

  2. Requirements: Define the utils.js module, encapsulate the base address and the function of calculating the sum of arrays, import it into index.js and use it to see the effect

  3. Export syntax:

    module.exports = {<!-- -->
      External attribute name: private variable within the module
    }
    
  4. Import syntax:

    const variable name = require('Module name or path')
    // For built-in modules in the Node.js environment, write the module name directly (for example: fs, path, http)
    // Custom module: write the module file path (for example: ./utils.js)
    

    The value of the variable name receives the object exported by the target module.

  5. Code

    • utils.js:export

      /**
       * Goal: Based on CommonJS standard syntax, encapsulate properties and methods and export them
       */
      const baseURL = 'http://hmajax.itheima.net'
      const getArraySum = arr => arr.reduce((sum, item) => sum + = item, 0)
      
      //Export
      module.exports = {<!-- -->
        url: baseURL,
        arraySum: getArraySum
      }
      
    • index.js: Import and use

      /**
       * Goal: Based on CommonJS standard syntax, import tool properties and methods
       */
      // import
      const obj = require('./utils.js')
      console.log(obj)
      const result = obj.arraySum([5, 1, 2, 3])
      console.log(result)
      

Summary

  1. How does the CommonJS standard specify how to export and import modules?

    Answer: Export: module.exports = {}, import: require(module name or path’)

  2. How to choose module name/path?

    Answer: Built-in module: Write name. For example: fs, path, http, etc. Custom module: write the module file path, for example: ./utils.js

ECMAScript Standard-Default Export and Import

Introduction

  1. The CommonJS specification is the default in the Node.js environment, and later the ECMAScript standard syntax was officially launched

  2. Export syntax:

    export default {<!-- -->
      External attribute name: private variable within the module
    }
    
  3. Import syntax:

    import variable name from 'module name or path'
    

    The value of the variable name receives the object exported by the target module.

  4. Note: Node.js only supports CommonJS standard syntax by default. If you want to use ECMAScript standard syntax in the current project environment, please create a new package.json file and set type: module’ to set it.

    {<!-- --> "type": "module" }
    
  5. Code:

    • utils.js:export

      /**
       * Goal: Based on ECMAScript standard syntax, encapsulate properties and methods and export them "by default"
       */
      const baseURL = 'http://hmajax.itheima.net'
      const getArraySum = arr => arr.reduce((sum, item) => sum + = item, 0)
      
      //Default export
      export default {<!-- -->
        url: baseURL,
        arraySum: getArraySum
      }
      
    • index.js:import

      /**
       * Target: Based on ECMAScript standard syntax, "default" import, tool properties and method usage
       */
      //default import
      import obj from './utils.js'
      console.log(obj)
      const result = obj.arraySum([10, 20, 30])
      console.log(result)
      

Summary

  1. How does the ECMAScript standard specify how modules are exported and imported by default?

    Answer: Export: export default {} Import: import variable name from module name or path’

  2. How to make Node.js switch module standard to ECMAScript?

    Answer: Go to the folder where the running module is located, create a new package.json and set {“type”: “module”}

ECMAScript Standard-Named Export and Import

Goals

Master the use of named exports and imports in ECMAScript standard syntax

Explanation

  1. There are many ECMAScript standard syntaxes, the commonly used ones are default and named export and import. In this lesson we will learn the use of named export and import.

  2. Requirements: Encapsulate and export the base address and array summation function, import them into index.js and use them to view the effect.

  3. Named export syntax:

    export modified definition statement
    
  4. Named import syntax:

    import {<!-- --> Variable with the same name } from 'Module name or path'
    

    Note: Variables with the same name refer to variable names exported within the module.

  5. Code example:

    • utils.js export

      /**
       * Goal: Based on ECMAScript standard syntax, encapsulate properties and methods and "name" them for export
       */
      export const baseURL = 'http://hmajax.itheima.net'
      export const getArraySum = arr => arr.reduce((sum, item) => sum + = item, 0)
      
      
    • index.js import

      /**
       * Goal: Based on ECMAScript standard syntax, "named" import, tool properties and method usage
       */
      // named import
      import {<!-- -->baseURL, getArraySum} from './utils.js'
      console.log(obj)
      console.log(baseURL)
      console.log(getArraySum)
      const result = getArraySum([10, 21, 33])
      console.log(result)
      
  6. How to choose with default export:

    • Load on demand, using named exports and imports
    • Load all, use default export and import

Summary

  1. Which 2 modularization standards does Node.js support?

    • CommonJS standard syntax (default)
    • ECMAScript standard syntax
  2. ECMAScript standard, syntax for named exports and imports?

    • Export: export statement that modifies the definition, import {variable with the same name} from module name or path’
  3. ECMAScript standard, default export and import syntax?

    • Export: export default {} Import: import variable name from module name or path’

The concept of package

Goals

Understand the concept of packages in the Node.js environment

Explanation

  1. Package: Integrate modules, code, and other data into a folder. This folder is called a package.

  2. Package classification:

    • Project package: mainly used for writing projects and business logic
    • Software packages: Encapsulate tools and methods for use
  3. Package requirements: There must be a package.json file in the root directory (recording the manifest information of the package)


  4. Package usage: When introducing a package folder into the code, the objects exported in the index.js module file under the package folder are introduced by default. If there is no index.js file, the objects specified by the main attribute in package.json will be introduced. Objects exported by the file module

  5. Requirements: A module that encapsulates the array summation function and a module that encapsulates the function for determining the length of username and password to form a software package and import it into index.js to view the effect

  6. Code example:

    • The utils/lib related code is ready, you just need to export it yourself in the utils/index.js unified export
    • utils/lib/arr.js
     // Array sum function
     const getArraySum = arr => arr.reduce((sum, item) => sum + = item, 0)
    
     module.exports = {<!-- -->
       getArraySum
     }
    
    • utils/lib/str.js
     const checkUserName = username => {<!-- -->
       return username.length >= 8
     }
    
     const checkPassWord = password => {<!-- -->
       return password.length >= 6
     }
    
     module.exports = {<!-- -->
       checkUser: checkUserName,
       checkPwd: checkPassWord
     }
    
    • utils/package.json
    {<!-- -->
      "name": "cz_utils",
      "version": "1.0.0",
      "description": "A package of common utility methods for arrays and strings",
      "main": "index.js",
      "author": "itheima",
      "license": "MIT"
    }
    
    • utils/index.js
    /**
     * This file is the only export of the utils toolkit
     * Function: Centralize all tool module methods and expose them to the outside in a unified manner
     */
    const {<!-- --> getArraySum } = require('./lib/arr.js')
    const {<!-- --> checkUser, checkPwd } = require('./lib/str.js')
    
    // Export all functions uniformly
    module.exports = {<!-- -->
      getArraySum,
      checkUser,
      checkPwd
    }
    ```
    
    
  • Use the package in server.js outside the utils package (note: this time the package folder is imported, not the module file)

    /**
     * Goal: Import the utils software package and use the tool functions encapsulated in it
     */
    const obj = require('./utils')
    console.log(obj)
    const result = obj.getArraySum([10, 20, 30])
    console.log(result)
    

npm package manager

Goals

Master package management with npm

Introduction to npm

  • npm is the standard package manager for Node.js. Used to download and manage packages in a Node.js environment.
  • As of January 2017, there were over 350,000 packages in the pm repository, making it the largest single-language code repository in the world, and there are certainly packages for just about everything.
  • It started as a way to download and manage Node.js package dependencies, but it has now become a tool used in front-end JavaScript as well.
  • npm is similar to maven in Java.

npm usage steps:

  1. Initialization manifest file: npm init -y (get package.json file, skip this command if available)

    Note that -y means using the default values for all options. Do not use Chinese/special symbols in the folder. It is recommended to use English and numbers. Because of the npm package name restrictions, it is recommended to use English and numbers or underscores and underscores.

  2. Download the package: npm i package name

  3. Use packages

  4. Requirements: Use npm to download the dayjs package to the local project folder, introduce it into index.js to format date printing, and run to observe the effect.

  5. Specific usage flow chart:

  6. Where will the downloaded package be stored?

    • node_modules under the current project and recorded in package.json

npm installs all dependencies

Goals

Master npm installation of all dependencies

Explanation

  1. We got a project written by someone else, but without node_modules, will the project run correctly?

    No, because there is a lack of dependent software packages required by the project, such as dayjs and lodash. If you do not have the corresponding source code in your project, the project will report an error.

  2. Why am I not given node_modules?

    Because everyone uses npm to download on their own machine, it is faster than transferring between disks (npm is cached on the local machine)

  3. How to get all the dependent software packages needed?

    Directly in the project directory, run the terminal command: npm i to install all packages and corresponding versions recorded in package.json to node_modules in this project

  1. Requirements: In the prepared material project, please install all the dependent software packages required by the project, and run the index.js code to see if it is normal!

Summary

  1. What should I do if there is only package.json but no node_modules in the current project?

    • In the current project directory, open a terminal and execute npm i to install all dependent software packages
  2. Why is node_modules not passed?

    • Because downloading with npm is cached on the local machine, it is faster than transferring between disks.

npm global software package-nodemon

Introduction

  1. Software package differences:

    • Local software package: used within the current project, encapsulating properties and methods, existing in node_modules
    • Global software package: used by all local projects, encapsulates commands and tools, and exists in the location of system settings
  2. The role of nodemon: replace the node command, detect code changes, and automatically restart the program

  3. use:

    1. Installation: npm i nodemon -g (-g represents installation into the global environment)
    2. Run: nodemon target js file to be executed
  4. Requirement: Use the nodemon command to start the project prepared in the material, then modify the code and save it, and observe the terminal to restart the application.

Summary of common commands in Node.js