node.js的模块化及reqire与exports释义

时间:2022-06-05
本文章向大家介绍node.js的模块化及reqire与exports释义,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

模块引入

模块化是node.js的核心概念,node.js对于服务端的操作都是封装成一个个独立的核心模块,以文件读写模块File System为例:

// 引入文件操作模块
let fs = require('fs')
let filePath = './data/清平调.md'
// 覆盖式写入数据
fs.writeFile(filePath, "云想衣裳花想容n", function (error) {})

// 追加写入
fs.appendFile(filePath, "春风拂槛露华浓n", function (error) {})

// 读取数据
fs.readFile(filePath, function (error, data) {
    console.log(data.toString())
})

执行结果:

☁  01 [master] ⚡ node 07.js
云想衣裳花想容
春风拂槛露华浓

node.js模块

require

node.js是经由require关键字引入模块,模块分为:自带的核心模块,自定义的模块。我们以自定义模块为例解析require的作用:

在同级目录下新建4个文件:

☁  custom_module [master] ⚡ tree
.
├── 01.js
├── 02.js
├── 03.js
├── 04.js

01.js

let poem = '云想衣裳花想容'
console.log(poem)

require('./02.js')

02.js

let poem = '春风拂槛露华浓'
console.log(poem)

require('./03.js')

03.js

let poem = '若非群玉山头见'
console.log(poem)

require('./04.js')

04.js

let poem = '会向瑶台月下逢'
console.log(poem)

01.js引入了02.js, 02.js引入了03.js, 03.js引入了04.js,这四个文件都有一个同名变量poem,让我们运行一下,看同名变量是否会被覆盖

☁  custom_module [master] ⚡ node 01.js
云想衣裳花想容
春风拂槛露华浓
若非群玉山头见
会向瑶台月下逢

由此可见,不同的模块有不同的命名空间,即使变量名称一致也不会相互污染。以上的侄子在require文件时,就直接执行此文件的内容,但如果我们是想调用模块里面的数据或方法呢?

此时,就需要使用exports将模块的变量/方法暴露出来,以供引用方调用。

exports

在node中,一个文件就是一个模块。实际上,为了让各个文件里的变量互不干扰,node让每个模块都放在一个闭包中执行,这样实现的模块的隔离。而要让模块间相互联系,就需要暴露变量。而exports就是负责对外暴露变量

05.js

let myExports = require('./06.js');
console.log(myExports);
console.log(myExports.name);
let name = '地球三体组织'
let goal = '消灭人类暴政,世界属于三体'
console.log(myExports.goal(name, goal));

06.js

let name = '三体'

exports.name = name

exports.goal = function (name, goal) {
    return name + '的目标是:' + goal
}

执行结果:

☁  custom_module [master] ⚡ node 05.js
{ name: '三体', goal: [Function] }
三体
地球三体组织的目标是:消灭人类暴政,世界属于三体

由此可知,exports是一个对象,如果模块要对外暴露变量,就需要将变量赋予作为exports的属性