Modularity in Node.js, npm package manager explained

Modularity in Node.js, npm package manager explained

The basic concept of modularity

What is modularity

Modularity refers to the process of dividing a system into several modules from top to bottom when solving a complex problem. For the entire system, modules are units that can be combined, decomposed and replaced.

Modules are the basic components of Node.js applications, and there is a one-to-one correspondence between files and modules. In other words, a Node.js file is a module, which may be JavaScript code, JSON, or a compiled C/C++ extension.

Modularity in programming means following fixed rules to split a large file into multiple independent and interdependent small modules.

The benefits of modular decomposition

  • Improved code reusability;
  • Improved code maintainability;
  • On-demand loading is possible.

Modularity in Node.js

Classification of modules in Node.js

In Node.js, modules are divided into three categories according to their sources:

1. Built-in modules (built-in modules are officially provided by Node.js, such as fs, path, http, etc.)

2. Custom modules (each .js file created by the user is a custom module)

3. Third-party modules (modules developed by third parties, not officially provided built-in modules, nor custom modules created by users, need to be downloaded before use)

Loading Modules

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

//Load the built-in fs module const fs = require('fs')
 
//Load user-defined module const custom = require('./custom.js')
 
//Load third-party modules const moment = require('moment')

Note : When you use the require() method to load other modules, the code in the loaded module will be executed

Module Scope

Similar to function scope, variables, methods and other members defined in a custom module can only be accessed within the current module. This module-level access restriction is called module scope.

//File: 01.custom.js
const username = '张三' //Define constant username in module scope
function sayHello(){
   console.log('Hello everyone, I am:' + username) //Define the function sayHello in the module scope
}
 
//File: 02.custom.js
const custom = require('./01.custom') //Import 01.custom file console.log(custom)  
// Output {} empty object. Private members in 01.custom.js module cannot be accessed in 02.custom.js module

Sharing module-scoped members outward

module object

There is a module object in each .js custom module, which stores information related to the current module.

In a custom module, you can use the module.exports object to share the members within the module for external use. When the outside world uses the require() method to import a custom module, what is obtained is the object pointed to by module.exports.

Note: When using the require() method to import a module, the result of the import is always based on the object pointed to by module.exports

For example:

//File: 01.custom.js
module.exports.username = 'zs' //Mount the attribute username on the module.exports object
module.exports.sayHello = function(){
   console.log('Hello') //Define the function sayHello in the module scope
}
module.exports = { //Let module.exports point to a new object nickname:'Xiao Ming',
   sayHi(){
     console.log('Hi!')
   }
}
 
//File: 02.custom.js
const custom = require('./01.custom.js') //Import 01.custom file console.log(custom)  
//Output { nickname:'Xiao Ming', sayHi:[Function:sayHi]}

exports object

Since the word module.exports is complicated to write, Node provides the exports object to simplify the code of sharing members externally. By default, exports and module.exports refer to the same object. The final sharing result is still based on the object pointed to by module.exports.

Misuse of exports and module.exports

When you require() a module, you always get the object pointed to by module.exports. Therefore, to prevent confusion, it is recommended not to use both exports and module.exports in the same module.

Note: Inside each module, the module variable represents the current module;

The module variable is an object, and its exports property (i.e. module.exports) is the external interface

Loading a module actually loads the module.exports property of the module. The require() method is used to load the module.

npm and packages

Bag

Third-party modules in Node.js are also called packages. Just like computer and computer refer to the same thing, third-party modules and packages refer to the same concept, just with different names.

Since the built-in modules of Node.js only provide some low-level APIs, the efficiency is very low when developing projects based on built-in modules. The package is encapsulated based on the built-in modules, providing a more advanced and convenient API, greatly improving development efficiency. The relationship between packages and built-in modules is similar to the relationship between jQuery and the browser's built-in API.

How to download the package

npm, Inc. provides a package management tool that we can use to download the required packages from the https://registry.npmjs.org/ server to local use. The name of this package management tool is Node Package Manager (npm package management tool for short). This package management tool is installed on the user's computer together with the Node.js installation package. You can execute the npm -v command in the terminal to view the version of the npm package management tool installed on your computer.

First, use the window logo plus R to open, and enter cmd, open the window and enter npm -v.

Command to install the package in the project

The software I use is WebStorm2021. The following instructions are all performed in the terminal of WebStorm2021 software.

npm install The full name of the package (When executing the npm install command, if you add the -g parameter at the end, the package will be installed as a global package.)

After the package is installed, we will see a folder called node_modules and a package-lock.json configuration file in the project folder.

The node_modules folder is used to store all packages installed in the project. When require() imports a third-party package, it searches and loads the package from this directory. The package-lock.json configuration file is used to record the download information of each package in the node_modules directory, such as the package name, version number, download address, etc.

Note: The installation package must be performed in a good network environment.

Install a specific version of the package

When you install a package using the npm install command, the latest version of the package will be automatically installed. If you need to install a specific version of a package, you can use the @ symbol after the package name to specify the specific version. For example: npm install [email protected]

Note: You can run the npm install command (or npm i) to install all dependent packages at once. (This is after removing the node_modules project).

Uninstall Package

The command to uninstall a package is: npm uninstall the full name of the package

Solve the problem of slow download speed

Why is the download speed slow?

When using npm to download packages, it is downloaded from the foreign https://registry.npmjs.org/ server by default. At this time, the transmission of network data needs to go through a long submarine optical cable, so the download speed will be very slow.

Solution 1 - Taobao NPM Mirror Server

Taobao has built a server in China that is specifically designed to synchronize packages from official overseas servers to domestic servers, and then provide package downloading services in China. Thereby greatly improving the speed of packaging. (Mirroring is a form of file storage, where the data on one disk exists as an identical copy on another disk.)

Solution 2 - Switch the npm package mirror source

The mirror source of the package refers to the server address where the package is downloaded.

Solution 3 - nrm

In order to switch the mirror source of the package more conveniently, we can install the nrm tool. Using the terminal commands provided by nrm, we can quickly view and switch the mirror source of the package

Summarize

This article ends here. I hope it can be helpful to you. I also hope that you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of modularization in Node.js
  • Detailed explanation of NodeJS modularity
  • Buffer object in Node.js and how to create it
  • Detailed explanation of the usage of the buffer object in node.JS binary operation module
  • Detailed explanation of nodeJS binary buffer object
  • Detailed explanation of Node.js modular mechanism and Buffer object

<<:  Use prometheus to count the remaining available percentage of MySQL auto-increment primary keys

>>:  Nginx Linux installation and deployment detailed tutorial

Recommend

Use Typescript configuration steps in Vue

Table of contents 1. TypeScript is introduced int...

HTML sample code for implementing tab switching

Tab switching is also a common technology in proj...

The use of vue directive v-bind and points to note

Table of contents 1. v-bind: can bind some data t...

SQL group by to remove duplicates and sort by other fields

need: Merge identical items of one field and sort...

Implementation of services in docker accessing host services

Table of contents 1. Scenario 2. Solution 3. Conc...

Create a virtual environment using venv in python3 in Ubuntu

1. Virtual environment follows the project, creat...

CSS eight eye-catching HOVER effect sample code

1. Send effect HTML <div id="send-btn&quo...

Two implementation codes of Vue-router programmatic navigation

Two ways to navigate the page Declarative navigat...

Detailed Example of Row-Level Locking in MySQL

Preface Locks are synchronization mechanisms used...

Using CSS3 to implement font color gradient

When using Animation.css, I found that the font o...

MySQL database terminal - common operation command codes

Table of contents 1. Add users 2. Change the user...

SVG+CSS3 to achieve a dynamic wave effect

A vector wave <svg viewBox="0 0 560 20&qu...

Implementing login page based on layui

This article example shares the specific code of ...

Docker+nacos+seata1.3.0 installation and usage configuration tutorial

I spent a day on it before this. Although Seata i...