search
HomeWeb Front-endJS TutorialWhat is modularity? Let's talk about Node modularity

What is modularity? This article will give you an in-depth analysis of Node modularity. I hope it will be helpful to you!

What is modularity? Let's talk about Node modularity

What is modularity

Modularization refers tosolving a complex When solving problems, it is a process of dividing the system into several modules layer by layer from top to bottom. For the entire system, modules are units that can be combined, decomposed and replaced.

The above definition is a bit obscure. Let me give you a simple example: the Overlord game console we played when we were children. When we got tired of playing a game, we It is impossible to directly replace a game console. We can experience various games by changing the game belt. This form is modularization, divides the game into small modules, and when we need it, we can just take it and insert it for use!

Modularization in our programming is actually following fixed rules and splitting a large file into individual pieces that are independent and interdependent of multiple small modules. [Related tutorial recommendations: nodejs video tutorial]

The benefits of splitting the code into modules:

  • improves the ## of the code #Reusability

  • Improves the

    maintainability of the code

  • can be achieved

    press Need to load(This is really easy to use!)

##Modular specification

Modularization specifications are
the rules that need to be followed when splitting and combining code in a modular manner.

For example:
?1. What syntax format is used to

reference the module
?2. What syntax format is used in the module Exposing members to the outside
Benefits of modular specifications: everyone complies with the same modular specifications to write code, which reduces the cost of communication and greatly facilitates mutual calls between various modules , Benefit others and yourself. (

Heima Ge’s summary is really in place

)

Module classification in node.jsBased on Node.js Depending on the source of the modules, the modules are divided into 3 major categories, namely:

? 1.

Built-in modules
(Built-in modules are officially provided by Node.js, such as fs, path, http, etc.) ? 2. Custom module
(Every .js file created by the user is a custom module) ? 3. Third-party module
(provided by a third party The developed modules are not officially provided built-in modules, nor are they custom modules created by users. They need to be downloaded before use)

We have learned about commonly used built-in modules in the above article, and the rest are The two modules below have relatively no features and depend more on the needs of the developer!

Load module##Use the powerful

require()
method, you can load the required

built-in modules, user-defined modules, and third-party modules for use. Note: When using the require() method to load other modules, the module will be executed. Load the code

in the module.

Module scope of node.js

What is module scope Domain

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

Code example:

//在模块作用域中定义常量 name
const name = 'qianmo'
//在模块作用域中定义函数sing()
function sing() {
    console.log(`大家好,我是${name}`);
}
//在测试js文件中加载模块
const a = require('./08.模块作用域')
console.log(a);  // {}
In the above code, we defined constants and methods in the module scope, but in the js under test After loading the module in the file and printing it, we found that what was printed was

empty object
. This is because the properties and methods in the module scope are private members and we cannot access them when loading the module!

Benefits of module scopeThere is actually only one benefit of module scope:Prevent the problem of global variable pollution

In the above code, we introduced two js files,

variable aWhat is modularity? Lets talk about Node modularity is defined in both js files at the same time , after we print a, we find that what is printed is
zs, here we can find a problem, the 2.js file overwrites 1.js, This reflects a problem. When we define global variables, it is easy to cause variable pollution. The modularization of node can help us solve this problem!?

向外共享模块作用域中的成员

module对象

在每个 .js 自定义模块中都有一个 module 对象,它里面存储了和当前模块有关的信息

我们打印一下module,console.log(module)

What is modularity? Lets talk about Node modularity

module.exports对象

在自定义模块中,可以使用 module.exports 对象,将模块内的成员共享出去,供外界使用
外界用 require() 方法导入自定义模块时,得到的就是 module.exports 所指向的对象

代码示例:

// 在默认情况下 module.exports = {}
const age = 20
//向 module.exports 对象上挂载 name 属性
module.exports.name = '正式'

//向 module.exports 对象上挂载 sing 方法
module.exports.sing = function() {
    console.log('hello');
}
module.exports.age = age

//让 module.exports 指向一个全新的对象
module.exports = {
    username : 'qianmo',
    hi() {
        console.log('你好啊!');
    }
}
// 在外界使用require 导入一个自定义模块的时候 得到的成员。
// 就是 那个模块中,通过 module.exports 指向的那个对象
const m1 = require('./11.自定义模块')
console.log(m1); // { username: 'qianmo', hi: [Function: hi] }

在测试js文件中,我们打印了引入的模块,发现打印出来了module.exports最后指定的对象
注意:使用 require() 方法导入模块时,导入的结果,永远以 module.exports 指向的对象为准。

exports对象

由于 module.exports 单词写起来比较复杂,为了简化向外共享成员的代码,Node 提供了 exports 对象默认情况下,exports 和 module.exports 指向同一个对象。最终共享的结果,还是以 module.exports 指向的对象为准

代码示例:

console.log(exports); // {}
console.log(module.exports); // {}

console.log(exports === module.exports); // true

在我们进行对exports对象解析之前,我们需要确定一下exportsmodule.exports是不是指向的是一个对象,我们可以看出,最后打印出了true,说明exportsmodule.exports指向的是一个对象!

const username = 'zs'
exports.username = username
exports.age = 20
exports.sayHello = function() {
    console.log('大家好!');
}

//最终向外共享的结果,永远是 module.exports 所指向的对象
const m = require('./13.exports对象')

console.log(m); //{ username: 'zs', age: 20, sayHello: [Function (anonymous)] }

在上述的代码中,我们在私有模块中定义了属性和方法,我们通过exports将属性和方法导出,在测试文件中引入,我们会发现,测试文件中打印出了属性和方法。

exports 和 module.exports 的使用误区

时刻谨记,使用require() 引入模块时,得到的永远是module.exports 指向的对象

What is modularity? Lets talk about Node modularity

  • 在第一个图中,module.exports指向一个新对象,所以在测试文件中,只会打印出来{gender:'男',age:22}

  • 在第二个图中,虽然exports指向了一个新对象,但是我们知道我们只会打印出来module.exports指向的对象,所以我们只能打印出来一个属性{username : 'zs'}

  • 在第三个图中,exports和module.exports都没有指定一个新对象,我们还知道,在默认情况下exports和module.exports指向的是一个对象,所以最终打印出来{username : 'zs',gender:'男'}

  • 在第四个图中,exports指向了一个新对象,但是最终这个对象又赋值给了module.exports,所以,最后打印出了{username:'zs',gender:'男',age:22}

? 注意 : 不要在一个文件中同时使用exportsmodule.exports,防止混淆

Node.js 中的模块化规范(commonJS)

Node.js 遵循了 CommonJS 模块化规范,CommonJS 规定了模块的特性各模块之间如何相互依赖

CommonJS 规定:
① 每个模块内部,module 变量代表当前模块
② module 变量是一个对象,它的 exports 属性(即 module.exports)是对外的接口
加载某个模块,其实是加载该模块的 module.exports 属性。require() 方法用于加载模块。

Summary

Modularization is the biggest feature of node.js. In front-end project development, modularization has become essential Part, The componentization we use in vue is actually the concept of modularity. As long as the front-end learns modularity thoroughly, your function encapsulation ability and on-demand calling ability will be greatly improved. In this way This will greatly improve your project development efficiency.

For more node-related knowledge, please visit: nodejs tutorial!

The above is the detailed content of What is modularity? Let's talk about Node modularity. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
Vercel是什么?怎么部署Node服务?Vercel是什么?怎么部署Node服务?May 07, 2022 pm 09:34 PM

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

node.js gm是什么node.js gm是什么Jul 12, 2022 pm 06:28 PM

gm是基于node.js的图片处理插件,它封装了图片处理工具GraphicsMagick(GM)和ImageMagick(IM),可使用spawn的方式调用。gm插件不是node默认安装的,需执行“npm install gm -S”进行安装才可使用。

火了!新的JavaScript运行时:Bun,性能完爆Node火了!新的JavaScript运行时:Bun,性能完爆NodeJul 15, 2022 pm 02:03 PM

今天跟大家介绍一个最新开源的 javaScript 运行时:Bun.js。比 Node.js 快三倍,新 JavaScript 运行时 Bun 火了!

nodejs中lts是什么意思nodejs中lts是什么意思Jun 29, 2022 pm 03:30 PM

在nodejs中,lts是长期支持的意思,是“Long Time Support”的缩写;Node有奇数版本和偶数版本两条发布流程线,当一个奇数版本发布后,最近的一个偶数版本会立即进入LTS维护计划,一直持续18个月,在之后会有12个月的延长维护期,lts期间可以支持“bug fix”变更。

聊聊Node.js中的多进程和多线程聊聊Node.js中的多进程和多线程Jul 25, 2022 pm 07:45 PM

大家都知道 Node.js 是单线程的,却不知它也提供了多进(线)程模块来加速处理一些特殊任务,本文便带领大家了解下 Node.js 的多进(线)程,希望对大家有所帮助!

node爬取数据实例:聊聊怎么抓取小说章节node爬取数据实例:聊聊怎么抓取小说章节May 02, 2022 am 10:00 AM

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!

深入浅析Nodejs中的net模块深入浅析Nodejs中的net模块Apr 11, 2022 pm 08:40 PM

本篇文章带大家带大家了解一下Nodejs中的net模块,希望对大家有所帮助!

怎么获取Node性能监控指标?获取方法分享怎么获取Node性能监控指标?获取方法分享Apr 19, 2022 pm 09:25 PM

怎么获取Node性能监控指标?本篇文章来和大家聊聊Node性能监控指标获取方法,希望对大家有所帮助!

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.