Node.js笔记 - XiaoMeimei/Notes GitHub Wiki
1.module原理
要在模块中对外输出变量,用:
module.exports = variable;
输出的变量可以是任意对象、函数、数组等等。
要引入其他模块输出的对象,用:
var foo = require('other_module');
引入的对象具体是什么,取决于引入模块输出的对象。
JavaScript里面并没有一种模块机制来保证不同模块可以使用相同变量。JavaScript中模块中变量是全局的,会互相影响,产生冲突。 Node.js实现模块功能的奥妙在于JavaScript是一种函数式编程语言,它支持闭包。一段代码如果用函数包裹起来的话,里面的变量就成了局部变量。
hello.js代码:
var s = 'welcome to Node.js!';
function greet(name) {
console.log(`${name}, ${s}`);
}
module.exports = greet;
Node.js加载之后的:这样一来,原来的全局变量s现在变成了匿名函数内部的局部变量。如果Node.js继续加载其他模块,这些模块中定义的“全局” 变量s也互不干扰。
(function () {
var s = 'welcome to Node.js!';
function greet(name) {
console.log(`${name}, ${s}`);
}
module.exports = greet;
})();
**模块的输出module.exports怎么实现?**
Node先准备好一个module
// 准备module对象:
var module = {
id: 'hello',
exports: {}
};
var load = function (module) {
// 读取的hello.js代码:
function greet(name) {
console.log('Hello, ' + name + '!');
}
module.exports = greet;
// hello.js代码结束
return module.exports;
};
var exported = load(module);
// 保存module:
save(module, exported);
可见,变量module是Node在加载js文件前准备的一个变量,并将其传入加载函数,我们在hello.js中可以直接使用变量module原因就在于它实际上是函数的一个参数:
module.exports = greet;
通过把参数module传递给load()函数,hello.js就顺利地把一个变量传递给了Node执行环境,Node会把module变量保存到某个地方。
由于Node保存了所有导入的module,当我们用require()获取module时,Node找到对应的module,把这个module的exports变量返回,这样,另一个模块就顺利拿到了模块的输出:
var greet = require('./hello');