Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the concept of modularity in Node.js

2025-03-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of "what is the concept of modularization in Node.js". The editor shows you the operation process through an actual case, and the operation method is simple, fast and practical. I hope this article "what is the concept of modularization in Node.js" can help you solve the problem.

I. the basic concept of modularization

1.1 what is modularization

Modularization refers to the process of dividing the system into several modules layer by layer from top to bottom when solving a complex problem. For the whole system, the module is a unit that can be combined, decomposed and replaced.

Modularization in the field of programming is to follow the fixed rules of splitting a large file into independent and interdependent small modules.

The benefits of modularizing the code:

Improve the reusability of the code

Improve the maintainability of the code

It can be loaded on demand.

II. Modularization in Node.js

2.1 Classification of modules in Node.js

According to the different sources of modules, modules are divided into three categories in Node.js, which are:

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

Custom module (every .js file created by the user is a custom module)

Third-party module (a module developed by a third party is not an official built-in module, nor is it a user-created custom module, which needs to be downloaded before use)

2.2 load module

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

Note: when you use the require () method to load other modules, the code in the loaded module is executed; loading the custom module omits the file suffix '.js'.

2.3 Module scope in Node.js

What is 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.

Benefits of module scope

Prevents global variable contamination (if two js files are imported with the script tag and the same variable is defined in both files, the former will be overwritten by the latter)

2.4 share members in the scope of the module outward

1. Module object

In each .js custom module, there is a module object that stores information about the current module, which is printed as follows:

2. Module.exports object

In the custom module, you can use the module.exports object to share the members of the module for external use.

When the outside world imports a custom module with the require () method, you get the object that module.exports points to.

3. Attention points when sharing members

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

4. Exports object

Because module.exports words are complex to write, to simplify the code for sharing members outward, Node provides an exports object. By default, exports and module.exports point to the same object. The final result of sharing is based on the object pointed to by module.exports.

5. Misunderstanding of exports and module.exports

Always keep in mind that when you require () module, you always get the object that module.exports points to:

Personal understanding: exports and module.exports originally point to the same object. Just by mounting the data pointing to the same object, the data mounted through exports can also be obtained by the require module. If one party assigns a value (pointing to another object, then they don't point to the same object, and the require module gets the object that module.exports points to, so once one party changes the direction, the require module won't get the value of exports.)

Note: to prevent confusion, it is recommended that you do not use exports and module.exports in the same module at the same time

The modularization specification Node.js in 2.5 Node.js follows the CommonJS modularization specification. CommonJS defines the characteristics of the modules and how the modules depend on each other.

CommonJS stipulates that:

(1) the module variable represents the current module within each module.

(2) the module variable is an object, and its exports attribute (that is, module.exports) is the external interface.

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

Third, npm and package

3.1 package

1. What is a bag

Third-party modules in Node.js are also called packages.

Just as computers and computers refer to the same thing, third-party modules and packages refer to the same concept, but with different names.

2. The source of the package

Unlike the built-in modules and custom modules in Node.js, packages are developed by third-party individuals or teams and are available to everyone for free.

Note: the packages in Node.js are free and open source and can be downloaded and used free of charge.

3. Why do you need a bag

Because the built-in module of Node.js only provides some underlying API, it is very inefficient when developing a project based on the built-in module.

The package is packaged based on the built-in module, which provides a more advanced and convenient API, which greatly improves the development efficiency.

The relationship between packages and built-in modules is similar to that between jQuery and the browser's built-in API.

4. Where to download the package

There is an IT company abroad, called npm, Inc. This company has a very famous website: www.npmjs.com/, which is the largest package sharing platform in the world. You can search any package you need from this website, as long as you are patient enough!

So far, more than 11 million developers around the world have developed and shared more than 1.2 million packages for our use through this package sharing platform. Npm, Inc. The company provides a server with the address of registry.npmjs.org/ to share all the packages, and we can download the packages we need from this server.

Note:

Search the package you need from the www.npmjs.com/ website

Download the package you need from the registry.npmjs.org/ server

5. How to download the package

Npm, Inc. The company provides a package management tool that we can use to download the required packages from the registry.npmjs.org/ server to local use.

This package management tool is called Node Package Manager (npm package Management tool for short). This package management tool is installed on the user's computer along with the Node.js installation package.

You can execute the npm-v command in the terminal to check the version number of the npm package management tool installed on your computer:

3.2 first experience of npm

1. Commands to install packages in the project

If you want to install a package with the specified name in your project, you need to run the following command:

Full name of the npm install package

The above packing command can be simplified into the following format:

Full name of the npm I package

2. Which files have been added after the initial packing?

After the initial package is completed, add a folder called node_modules and a configuration file for package-lock.json under the project folder.

The node_modules folder is used to store all packages that have been installed into the project. When require () imports a third-party package, it looks for 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, and so on.

Note: programmers should not manually modify any code in node_modules or package-lock.json files, npm package management tools will automatically maintain them.

3. Install the specified version of the package

By default, the latest version of the package is automatically installed when you use the npm install command to install the package. If you need to install a specified version of the package, you can specify the specific version with the @ symbol after the package name, for example:

Npm i moment@2.22.2

4. Semantic version specification of package

The version number of the package is defined in dotted decimal form, with a total of three digits, such as 2.24.0

Each of these digits represents the following meaning:

First digit: large version

Second digit: feature version

Third digit: Bug fix version

The rule of version number promotion: as long as the previous version number increases, the subsequent version number returns to zero.

3.3 package Management Profil

Npm states that a package management configuration file called package.json must be provided in the project root directory. Used to record some configuration information related to the project. For example:

The name, version number, description, etc of the project

Which packages are used in the project?

Which packages will be used only during development

Those packages need to be used in development and deployment

1. The problem of multi-person cooperation

Problem encountered: the size of the third-party package is too large to share the project source code among team members.

Solution: eliminate node_modules when sharing

2. How to record which packages are installed in the project

In the project root directory, create a configuration file called package.json, which can be used to record which packages are installed in the project. This makes it easy to share the source code of the project among team members after removing the node_modules directory.

Note: in future project development, be sure to add the node_modules folder to the .gitignore ignore file.

3. Quickly create package.json

The npm package management tool provides a shortcut command to quickly create the package management configuration file package.json in the directory where the command is executed:

Npm init-y

Note:

(1) the above command can only be run successfully in the English directory! Therefore, the name of the project folder must be named in English, not in Chinese, and no spaces can appear.

(2) @ when you run the npm install command to install the package, the npm package management tool will automatically record the name and version number of the package in package.json.

Special note: the current version of the installation package will automatically generate package.json.

4. Dependencies node

In the package.json file, there is a dependencies node that records which packages you installed using the npm install command.

5. Install all packages at once

When we get a project without node_modules, we need to download all the packages to the project before we can get the project up and running. Otherwise, an error similar to the following will be reported:

You can run the npm install command (or npm I) to install all dependent packages at once:

6. Uninstall the package

You can run the npm uninstall command to uninstall the specified package:

Npm uninstall specific package name

Note: after the successful execution of the npm uninstall command, the uninstalled package will be automatically removed from the dependencies of package.json. There is no abbreviation for uninstalling.

7. DevDependencies node

If some packages are used only during the development phase of the project, but not after the project is launched, it is recommended that you log these packages to the devDependencies node.

Correspondingly, if some packages need to be used after the development and the project are online, it is recommended that you log these packages to the dependencies node.

You can log the package to the devDependencies node using the following command:

3.4 solve the problem of slow downloading speed

1. Why is the speed of downloading slow?

When using npm to download the package, it is downloaded from a foreign registry.npmjs.org/ server by default, so the download speed will be very slow.

2. Taobao NPM image server

Taobao has set up a server in China to synchronize packages from foreign official servers to domestic servers, and then provide contracted services at home. Thus greatly improve the speed of the package.

Extension: Mirroring is a form of file storage in which data on one disk has an identical copy on another disk.

3. Switch the packet image source of npm.

The image source of the package refers to the server address of the package.

4 、 nrm

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

3.5 packet classification

Packages downloaded using the npm package management tool are divided into two categories, namely:

Project package

Global package

1. Project package

The packages that are installed into the project's node_modules directory are project packages.

The project package is divided into two categories, namely:

Development dependency packages (packages that are recorded in the devDependencies node and used only during development)

Core dependency packages (packages recorded in the dependencies node that are used during development and after the project is online)

2. Global package when executing the npm install command, if the-g parameter is provided, the package will be installed as a global package.

The global package is installed in the C:\ Users\ user directory\ AppData\ Roaming\ npm\ node_modules directory.

Note:

(1) only packages of a tool nature are necessary for global installation. Because they provide useful terminal commands.

(2) to determine whether a package needs to be installed globally before it can be used, you can refer to the official instructions.

3 、 i5ting_toc

I5ting_toc is a gadget that converts md documents into html pages. The steps are as follows:

3.6 canonical packet structure

After knowing the concept of the package and how to download and use the package, let's take a closer look at the internal structure of the package.

A standard package, its composition and structure, must meet the following three requirements:

(1) packages must exist in a separate directory

(2) the package management configuration file package.json must be included in the top directory of the package.

(3) the package.json must contain the three attributes of name,version,main, which represent the name, version number and entry of the package, respectively.

Note: the above three requirements are a format that a standard package structure must follow. For more constraints, please refer to the following website: https://yarnpkg.com/zh-Hans/docs/package-json

3.7 develop your own package

1. The basic structure of initialization package

(1) create a new itheima-tools folder as the root of the package

(2) in the itheima-tools folder, create the following three files:

Package.json (package Management profile)

Index.js (entry file for the package)

README.md (documentation for the package)

2. Initialize package.json

Note: name- is used to tell the name of the application or software package; version- indicates the current version; main- sets the entry point of the application; description is a short description of the application / software package; keywords- this property contains an array of keywords related to the function of the package (to help browse the node website to find the package); license- specifies the license of the package.

3. Write the documentation for the package

The README.md file in the root directory of the package is the documentation for using the package. Through it, we can write the instructions for the use of the package in markdown format in advance for users' reference.

There is no mandatory requirement for what is written in the README file; as long as the function, usage and precautions of the package can be clearly described.

3.8 release package

1. Sign up for a npm account

(1) visit the www.npmjs.com/ website and click the sign up button to enter the registration user interface

(2) enter the information related to the account: Full Name, Public Email, Username, Password

(3) Click the Create an Account button to register an account

(4) Log in to email and click the verification link to verify the account.

2. Log in to npm account

After the registration of the npm account is completed, you can execute the npm login command in the terminal and enter the user name, password (the password is hidden, can not be seen, just enter the correct enter), the mailbox, and the OTP code sent to the mailbox to log in successfully.

Note: before running the npm login command, you must change the server address of the package to the official server of npm. (if you used the taobao server before, you must switch to the official npm server.) otherwise, it will cause the release of the package to fail!

3. Publish the package to npm

After changing the terminal to the root directory of the package, run the npm publish command to publish the package to npm (Note: the package name cannot be the same, you can check the official website to see if there is a package with the same name).

4. Delete published packages

Run the npm unpublish package name-- force command to remove the published package from npm.

Note:

(1) npm unpublish command can only delete packages released within 72 hours.

(2) packages deleted by npm unpublish are not allowed to be released repeatedly within 24 hours.

(3) be careful when releasing packages and try not to publish meaningless packages on npm!

Fourth, the loading mechanism of the module

4.1 priority loading from cache

The module is cached after the first load. This also means that multiple calls to require () do not cause the module's code to be executed multiple times.

Note: whether they are built-in modules, user-defined modules, or third-party modules, they will be loaded from the cache first, thus improving the loading efficiency of the module.

4.2 loading mechanism of built-in modules

The built-in module is officially provided by Node.js, and the built-in module has the highest loading priority.

For example: require ('fs') always returns the built-in fs module, which is called fs even if there is a package with the same name in the node_modules directory.

4.3 loading mechanism of custom module

When you load a custom module using require (), you must specify a path identifier that starts with. / or.. /. When loading a custom module, if a path identifier such as. / or.. / is not specified, node loads it as a built-in module or a third-party module.

At the same time, when importing a custom module using require (), if the file extension is omitted, Node.js attempts to load the following files in order:

(1) load according to the exact file name

(2) complete the .js extension to load

(3) complete the .json extension to load

(4) complete the .node extension to load

(5) failed to load and terminal reported an error

4.4 loading mechanism of third-party modules

If the module identifier passed to require () is not a built-in module and does not start with'. /'or'.. /', Node.js will try to load a third-party module from the / node_modules folder, starting with the parent directory of the current module.

If the corresponding third-party module is not found, move to the next parent directory and load it to the root of the file system.

For example, if require ('tools') is called in the' C:\ Users\ itheima\ project\ foo.js' file, Node.js looks in the following order:

(1) C:\ Users\ itheima\ project\ node_modules\ tools

(2) C:\ Users\ itheima\ node_modules\ tools

(3) C:\ Users\ node_modules\ tools

(4) C:\ node_modules\ tools

4.5 directory as a module

When you pass the directory as a module identifier to require () for loading, there are three ways to load:

(1) look for a file called package.json in the loaded directory, and look for the main attribute as the entry for loading require ()

(2) if there is no package.json file in the directory, or if the main entry does not exist or cannot be parsed, Node.js will attempt to load the index.js file in the directory.

(3) if both of the above steps fail, Node.js will print an error message on the terminal to report the missing module: Error: Cannot find module 'xxx'

This is the end of the introduction to "what is the concept of Modularization in Node.js". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report