What is modularity? This article will give you an in-depth analysis of node modularization. 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!
[Related tutorial recommendations: nodejs video tutorial, Programming teaching】
Modularization in our programming is actually following fixed Rule
, split a large file into multiple small modules that are independent and
dependent
Benefits of code module splitting:
- Improved the
reusability of the code
- Improved the
maintainability of the code
- can be implemented on demand
Loading
(This is really easy to use!)
##Modular specification
Modular specifications are the 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:
//在模块作用域中定义常量 nameconst 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, variables are defined in the js files at the same time a
zs, here we can find a problem, the
2.js file overwrites the
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 = 20exports.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() 方法用于加载模块。
小结
模块化是node.js最大的特点,在前端的项目开发中,模块化已经成为了必不可少的部分,
我们在vue中使用的组件化其实就是模块化的概念
,前端只要学透了模块化,那么你的函数封装能力,按需调用的能力将会大大提升,这样的话将会极大限度的提升你的项目开发效率。
For more node-related knowledge, please visit: nodejs tutorial!
The above is the detailed content of What is modularity? An in-depth analysis of node modularization. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


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

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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