创建模块
在 Node.js 中,创建一个模块非常简单,如下我们创建一个 main.js 文件,代码如下:
var hello = require('./hello');
hello.world();
复制代码
以上实例中,代码 require('./hello') 引入了当前目录下的 hello.js 文件(./ 为当前目录,node.js 默认后缀为 js)。
Node.js 提供了 exports 和 require 两个对象,其中 exports 是模块公开的接口,require 用于从外部获取一个模块的接口,即所获取模块的 exports 对象。
接下来我们就来创建 hello.js 文件,代码如下:
exports.world = function() {
console.log('Hello World');
}
复制代码
在以上示例中,hello.js 通过 exports 对象把 world 作为模块的访问接口,在 main.js 中通过 require('./hello') 加载这个模块,然后就可以直接访 问 hello.js 中 exports 对象的成员函数了。
有时候我们只是想把一个对象封装到模块中,格式如下:
module.exports = function() {
// ...
}
复制代码
例如:
hello.js
function Hello() {
var name;
this.setName = function(thyName) {
name = thyName;
};
this.sayHello = function() {
console.log('Hello ' + name);
};
};
module.exports = Hello;
复制代码
这样就可以直接获得这个对象了:
main.js
var Hello = require('./hello');
hello = new Hello();
hello.setName('BYVoid');
hello.sayHello();
复制代码
模块接口的唯一变化是使用 module.exports = Hello 代替了exports.world = function(){}。 在外部引用该模块时,其接口对象就是要输出的 Hello 对象本身,而不是原先的 exports。
值得注意的是,exports是module.exports的一个引用,可以理解成 exports = module.exports。
模块(require)加载顺序
从文件模块缓存中加载
尽管原生模块与文件模块的优先级不同,但是都会优先从文件模块的缓存中加载已经存在的模块。
从原生模块加载
原生模块的优先级仅次于文件模块缓存的优先级。require 方法在解析文件名之后,优先检查模块是否在原生模块列表中。以http模块为例,尽管在目录下存在一个 http/http.js/http.node/http.json 文件,require("http") 都不会从这些文件中加载,而是从原生模块中加载。
原生模块也有一个缓存区,同样也是优先从缓存区加载。如果缓存区没有被加载过,则调用原生模块的加载方式进行加载和执行。
从文件加载
当文件模块缓存中不存在,而且不是原生模块的时候,Node.js 会解析 require 方法传入的参数,并从文件系统中加载实际的文件,加载过程中的包装和编译细节在前一节中已经介绍过,这里我们将详细描述查找文件模块的过程,其中,也有一些细节值得知晓。
require方法接受以下几种参数的传递:
http、fs、path等,原生模块。 ./mod或../mod,相对路径的文件模块。 /pathtomodule/mod,绝对路径的文件模块。 mod,非原生模块的文件模块。
exports 和 module.exports 的使用:
如果要对外暴露属性或方法,就用 exports 就行,要暴露对象(类似class,包含了很多属性和方法),就用 module.exports。
不建议同时使用 exports 和 module.exports。
如果先使用 exports 对外暴露属性或方法,再使用 module.exports 暴露对象,会使得 exports 上暴露的属性或者方法失效。
原因在于,exports 仅仅是 module.exports 的一个引用。在 nodejs 中,是这么设计 require 函数的:
function require(...){
var module = {exports: {}};
((module, exports) => {
function myfn () {}
// 这个myfn就是我们自己的代码
exports.myfn = myfn; // 这里是在原本的对象上添加了一个myfn方法。exports是module.exports的引用,指向了原来module.exports的内存地址,即原来对象的内存地址。
module.exports = myfn;// 这个直接把当初的对象进行覆盖。这里,其实就是module.exports的内存地址改变了指向了myfn,但上面exports的引用并没有变
})(module,module.exports)
return module.exports;
}
复制代码