10-Node.js Modularity

01. Introduction to modularization

Goals

Learn about modularization concepts and benefits, and CommonJS standard syntax for exporting and importing

Explanation

  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

?

  1. Moreover, the project is composed of multiple modules, each module is independent, and improves module code reusability, on-demand loading, and independent scope.

  2. 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

  3. 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

  4. Export syntax:

    module.exports = {<!-- -->
      External attribute name: private variable within the module
    }
    
  5. 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.

  6. 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. What is modularity in Node.js?

    Answer

    • Each file is an independent module
  2. How are the modules connected?

    Answer

    • Use specific syntax for exporting and importing using
  3. How does the CommonJS standard specify how to export and import modules?

    Answer

    • Export: module.exports = {}, import: require(‘module name or path’)
  4. 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

02.ECMAScript Standard-Default Export and Import

Goals

Master the use of default export and import in ECMAScript standard syntax

Explanation

  1. The CommonJS specification is the default in the Node.js environment. Later, the ECMAScript standard syntax was officially launched. Next, we will experience how to use the default export and import syntax in this standard in a requirement.

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

  3. Export syntax:

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

    import variable name from 'module name or path'
    

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

  5. 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" }
    
  6. 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

    • Run the folder where the module is located, create a new package.json and set {“type”: “module”}

03.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?

    Answer

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

    Answer

    • 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?

    Answer

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

04. 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 file section 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 in the material, you only need to export it yourself in the unified export of 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
      }
      
      
    • Index.js is used to import the software package folder (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)
      

Summary

  1. What is a package?

    Answer

    • A folder that aggregates modules, code, and other materials
  2. What are the 2 categories of packages?

    Answer

    • Project package: a folder for writing project code, software package: encapsulating tools and methods for developers to use
  3. What is the role of package.json file?

    Answer

    • Record the name, author, entry file and other information of the software package
  4. When importing a package folder, which file is imported?

    Answer

    • The default index.js file, or the file specified by the main attribute

05.npm package manager

Goals

Master package management with npm

Explanation

  1. npm profile link: Package manager for downloading and managing packages in a Node.js environment

  2. 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 restrictions on npm package names, it is recommended to use English and numbers or underscores and underscores.

    2. Download the package: npm i package name

    3. Use packages

  3. 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.

  4. Specific usage flow chart:

Summary

  1. What is the role of npm package manager?

    Answer

    • Download packages and manage versions
  2. Initialize the project manifest file package.json command?

    Answer

    • npm init -y
  3. Command to download package?

    Answer

    • npm i package name
  4. Where will the downloaded package be stored?

    Answer

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

06.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

  4. 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?

    Answer

    • 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?

    Answer

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

07.npm global software package-nodemon

Goals

Master the difference between local software packages and global software packages, and experience the use of nodemon

Explanation

  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

  1. What is the difference between local software packages and global software packages?

    Answer

    • Local software package, acting on the current project, encapsulating properties and methods
    • Global software package, used by all local projects, encapsulates commands and tools
  2. What does nodemon do?

    Answer

    • Replace the node command, detect code changes, and automatically restart the program
  3. How to use nodemon?

    Answer

    • First make sure to install npm i nodemon -g
    • Use nodemon to execute the target js file

08. Summary of Node.js concepts and common commands

Goals

Summarize the modular syntax, package concepts and common commands learned above

Explanation

  1. Node.js modularization: treat each file as a module, with independent scope, load on demand, export and import using specific standard syntax

    CommonJS standard: generally used in Node.js project environment

    ECMAScript standard: generally used in front-end engineering projects

  2. Node.js package: a package that aggregates module files, code files, and other data into a folder

    Project package: a folder for writing project requirements and business logic

    Software package: a folder that encapsulates tools and methods for use (generally managed using npm)

    • Local software package: It acts on the current project and encapsulates properties/methods for the project to call and write business requirements.
    • Global software package: Acts on all projects, generally encapsulated commands/tools to support project operation

  3. Node.js common commands:

This is a basic question when using npm;
simply put:

  • Using the command –save (npm install name -S) or not writing the command –save will record the information into dependencies;
    The files recorded in dependencies are all files needed when the project is running;
  • Using the command –save-dev abbreviation (npm install name -D) will record the information into devDependencies;
    Recorded in devDependencies are some files that need to be used during the development process of the project, which are not needed when the project is finally run;
    In other words, after we complete the development, these files will not be needed in the final project;

Summary

  1. What is the command to install local packages?

    Answer

    • npm i package name

09.Express quickly builds Web services

Goals

Quickly build web services based on express local software package

Explanation

  1. Express definition link: Based on the Node.js platform, a fast, open, and minimalist web development framework

  2. Concept: Use express local software package to quickly build web services (based on http module)

  3. Function: Develop Web services, provide data interfaces, and provide web resources for browser use

  4. Requirements: Write a web service based on express, monitor the get request method and / path, and return a prompt string if someone requests it

  5. use:

    1. Download the express local software package to the project

    2. Import express to create a Web service object

    3. Monitor the request method and request path and return a prompt string

    4. For other request methods and request paths, a 404 prompt is returned by default.

    5. Listen to the port number, start the web service, and request the test in the browser

  6. code show as below:

    /**
     * Goal: Based on the express local software package, develop Web services and return resources to the requester
     */
    // 1. Download the express package
    // 2. Import and create Web service objects
    const express = require('express')
    const server = express()
    
    // 3. The method to monitor the request and the requested resource path
    server.get('/', (req, res) => {<!-- -->
      res.send('Hello, welcome to Express')
    })
    
    // 4. Monitor any requested method and requested resource path
    server.all('*', (req, res) => {<!-- -->
      res.status(404)
      res.send('The resource path you want to access does not exist')
    })
    
    // 5. Listen to the port number and start the Web service
    server.listen(3000, () => {<!-- -->
      console.log('Web service has started')
    })
    

Summary

  1. What is the role of express package?

    Answer

    • Quickly build web services based on Node.js to provide data interfaces and web resource access

10. Case-Getting Province List Interface

Goals

Based on express Web service, write an interface that provides province list data

Explanation

  1. Requirements: Based on express, develop an interface that provides province list data

  2. Steps: Monitor the /api/province path of the get request method, and read the province data in province.json and return it to the requester

  3. Core code:

    // Listen to the get request method, listen to the resource path /api/province, and read the province.json province data and return it
    server.get('/api/province', (req, res) => {<!-- -->
      fs.readFile(path.join(__dirname, 'data/province.json'), (err, data) => {<!-- -->
        res.send(data.toString())
      })
    })
    

Summary

  1. How does the Web service object created by express monitor the front-end request method?

    Answer

    • Just call the method with the same name as the request method. As soon as the parameter is passed in, the request resource path to be monitored will be executed. The subsequent callback function will be executed only after it is hit.

11. Browser’s same-origin policy

Goals

Master the concept and role of the same origin policy, as well as the restrictions of the same origin policy on AJAX

Explanation

  1. Same-origin policy: It restricts documents from one source or loaded JS scripts from interacting with resources from another source, helping us block malicious documents and reduce attack vectors

  2. For example: the phishing website collects information, uses AJAX to initiate malicious requests, and transmits transfer information to the bank server (cross-site forged request attack)

  3. Source refers to: protocol, domain name, port number.

  4. Same source: The source when the web page is loaded is the same as the source (protocol, domain name, port number) when the AJAX request is made, so the example just now is not a same-origin access, their domain names are different

  5. Function: The browser’s same-origin policy protects the security of websites in the browser and restricts AJAX to only initiate requests to same-origin URLs.

Summary

  1. What is the same origin policy?

    Answer

    • Restrict one source from interacting with another source’s resources
  2. What are the limitations of the same-origin policy?

    Answer

    • Restrict AJAX to only access same-origin URLs
  3. Under what circumstances is it homologous?

    Answer

    • If the source where the web page is loaded is the same as the source when the AJAX request is made (protocol, domain name, port number), it is the same origin.

12. Cross-domain issues

Goals

Master the concept of cross-domain and cross-domain problems

Explanation

  1. Cross-domain: From a document/script from one source, loading resources from another source results in cross-domain

  2. For example: if there is a difference between the source where the web document is opened and the source of AJAX access (protocol, domain name, port), cross-domain access occurs.

  3. When a cross-domain access occurs to a web page, the following error will be reported in the browser control:

    Access to XMLHttpRequest means: There is a problem with the XHR link, from a source (http://localhost:5500 cross-domain access http://localhost:3000)

  4. Requirements: Start the web page in LiveServer’s Web service, use AJAX to access the province list interface provided by the local Web service, and experience cross-domain issues. The index.html code is as follows:

    //Goal: Request the province list data provided by the native web service
    axios({<!-- -->
      url: 'http://localhost:3000/api/province',
      // method: 'get'
    }).then(res => {<!-- -->
      console.log(res)
    }).catch(err => {<!-- -->
      console.log(err)
    })
    

Summary

  1. What is cross-domain access?

    Answer

    • Cross-domain access occurs when the source of the web page and the source of the AJAX request (protocol, domain name, port number) are not exactly the same.

13. Cross-domain problem-solution 1-CORS

Goals

Master the development environment and solve cross-domain problems with CORS

Explanation

  1. Goal: A project with separate front-end and back-end. The front-end and back-end are not from the same source, and data communication must be ensured.

  2. Solution: Use CORS (Cross-Origin Resource Sharing), an HTTP header-based mechanism that accesses resources on the loading server by allowing the server to identify sources (domains, protocols, or ports) other than its own.

  3. Idea:

    • Server side: Set the Access-Control-Allow-Origin response header field to allow sources other than itself to access its resources.
    • Front-end: AJAX request is initiated normally, no additional operations are required
  4. step:

    1. Download the cors local package
    2. Import cors function
    3. Use server.use() to add plug-in functionality to the web service
    4. Pass the cors function call to the web service and start the test
  5. Set response header code

    // 2. Import cors function
    const cors = require('cors')
    // 3. Use server.use() to add plug-in functionality to the Web service
    server.use(cors())
    

Summary

  1. Why solve cross-domain issues?

    Answer

    • Because projects with separate front-end and back-end are not developed from the same source, communication between data needs to be ensured.
  2. How to solve cross-domain issues?

    Answer

    • Let the backend enable CORS cross-domain resource sharing and set Access-Control-Allow-Origin: ‘*’ in the response header.

14. Cross-domain problem-solution 2-same source access

Goals

Master cross-domain problem solving and same-origin access in production environment

Explanation

  1. Goal: Use cors in the development environment, turn off cors during online deployment, and adopt same-origin access method

  2. Method: Let the back-end web service provide a data interface and return web resources

  3. Advantages: Security, the back-end interface does not allow access from non-original sources

  4. Code: express sets up to expose the public folder as a static resource directory for direct access by the browser, and the html web page inside can be accessed

    // Expose the specified folder so that the front end can directly access it by splicing the path and resource name.
    server.use(express.static(path.join(__dirname, 'public')))
    

Summary

  1. At what stage of projects is CORS only applicable?

    Answer

    • Local development stage projects
  2. When the project goes online, how to solve cross-domain issues?

    Answer

    • Deploy the front-end project and the back-end project to the same source for access