详解Node.js API系列 Module模块(2) 案例分析

释放双眼,带上耳机,听听看~!

API文档是枯燥的,下面本人收集了一些论坛经常有人疑问和开源代码中经常遇到的案例供大家研究一下。

http://blog.whattoc.com/2013/09/11/nodejs_api_module_2md/

module.exports与exports的区别

每一个node.js执行文件,都自动创建一个module对象,同时,module对象会创建一个叫exports的属性,初始化的值是 {}


1
2
1module.exports = {};
2

Node.js为了方便地导出功能函数,node.js会自动地实现以下这个语句

foo.js


1
2
3
4
5
1exports.a = function(){
2    console.log('a')
3}
4exports.a = 1
5

test.js


1
2
3
1var x = require('./foo');
2console.log(x.a)
3

看到这里,相信大家都看到答案了,exports是引用 module.exports的值。module.exports 被改变的时候,exports不会被改变,而模块导出的时候,真正导出的执行是module.exports,而不是exports

再看看下面例子

foo.js


1
2
3
4
5
6
1exports.a = function(){
2    console.log('a')
3}
4module.exports = {a: 2}
5exports.a = 1
6

test.js


1
2
3
1var x = require('./foo');
2console.log(x.a)
3

result:


1
2
12
2

exports在module.exports 被改变后,失效。

是不是开始有点廓然开朗,下面将会列出开源模块中,经常看到的几个使用方式。

module.exports = View


1
2
3
4
5
6
7
8
9
10
11
12
13
14
1function View(name, options) {
2  options = options || {};
3  this.name = name;
4  this.root = options.root;
5  var engines = options.engines;
6  this.defaultEngine = options.defaultEngine;
7  var ext = this.ext = extname(name);
8  if (!ext && !this.defaultEngine) throw new Error('No default engine was specified and no extension was provided.');
9  if (!ext) name += (ext = this.ext = ('.' != this.defaultEngine[0] ? '.' : '') + this.defaultEngine);
10  this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express);
11  this.path = this.lookup(name);
12}
13module.exports = View;
14

javascript里面有一句话,函数即对象,View 是对象,module.export =View, 即相当于导出整个view对象。外面模块调用它的时候,能够调用View的所有方法。不过需要注意,只有是View的静态方法的时候,才能够被调用,prototype创建的方法,则属于View的私有方法。

foo.js


1
2
3
4
5
6
7
8
9
10
1function View(){
2}
3View.prototype.test = function(){
4    console.log('test')
5}
6View.test1 = function(){
7    console.log('test1')
8}
9module.exports = View
10

test.js


1
2
3
4
5
6
1var x = require('./foo');
2console.log(x)  //{ [Function: View] test1: [Function] }
3console.log(x.test)  //undefined
4console.log(x.test1) //[Function]
5x.test1()       //test1
6

var app = exports = module.exports = {};

其实,当我们了解到原理后,不难明白这样的写法有点冗余,其实是为了保证,模块的初始化环境是干净的。同时也方便我们,即使改变了 module.exports 指向的对象后,依然能沿用 exports的特性


1
2
3
4
5
6
1exports = module.exports = createApplication;
2/**
3 * Expose mime.
4 */
5exports.mime = connect.mime;
6

例子,当中module.exports = createApplication改变了module.exports了,让exports失效,通过exports = module.exports的方法,让其恢复原来的特点。

exports.init= function(){}

这种最简单,直接就是导出模块 init的方法。

var mongoose = module.exports = exports = new Mongoose;

集多功能一身,不过根据上文所描述的,大家应该不能得出答案。

给TA打赏
共{{data.count}}人
人已打赏
安全技术

对称加密与非对称加密优缺点详解

2021-8-18 16:36:11

安全技术

C++ 高性能服务器网络框架设计细节

2022-1-11 12:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索