What 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
Modularization refers to
solving 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 arethe rules that need to be followed when splitting and combining code in a modular manner.?1. What syntax format is used toFor example:
reference the module ?2. What syntax format is used in the module
Exposing members to the outsideBenefits 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. (
)
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)
require()
method, you can load the requiredbuilt-in modules, user-defined modules, and third-party modules
in the module.for use.
Note:
When using the require() method to load other modules, the module will be executed. Load the code
Module scope of node.js
# is similar to function scope. Variables, methods and other members defined in a custom module can only be accessedwithin 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); // {}
. 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
variable a 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!?
向外共享模块作用域中的成员
在每个 .js 自定义模块中都有一个 module 对象,
它里面存储了和当前模块有关的信息
我们打印一下module,console.log(module)
:
在自定义模块中,可以使用
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 指向的对象为准。
由于 module.exports 单词写起来比较复杂,
为了简化向外共享成员的代码,Node 提供了 exports 对象
。默认情况下,exports 和 module.exports 指向同一个对象
。最终共享的结果,还是以 module.exports 指向的对象为准
。
代码示例:
console.log(exports); // {} console.log(module.exports); // {} console.log(exports === module.exports); // true
在我们进行对exports对象解析之前,我们需要确定一下exports
与module.exports
是不是指向的是一个对象,我们可以看出,最后打印出了true
,说明exports
与module.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 指向的对象
:
在第一个图中,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}
? 注意 : 不要在一个文件中同时使用
exports
和module.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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

Yes, Node.js can be used for front-end development, and key advantages include high performance, rich ecosystem, and cross-platform compatibility. Considerations to consider are learning curve, tool support, and small community size.
