2. module对象
Node内部提供一个Module
构建函数,所有函数都是Module
的实例。
function Moudle(id,parent) {
this.id = id;
this.exports = {};
this.parent = paremt;
//...
}
每个模块内部,都有一个module
对象,代表当前模块。它有以下属性。
>
module.id
模块的识别符,通常是带有绝对路径的模块文件名>
module.filename
模块的文件名,带有绝对路径。>
module.loaded
返回一个布尔值,表示模块是否已经完成加载>
module.parent
返回一个对象,表示调用该模块的模块>
module.children
返回一个数组,表示该模块要用到的其他模块。>
module.exports
表示模块对外输出的值
下面是一个示例文件,最后一行输出module变量。
//example.js
var jquery = require('jquery');
exports.$ = jquery;
console.log(module);
执行这个文件,命令行会输出如下信息。
{ id: '.',
exports: { '$': [Function] }, //对外输出值
parent: null, // 调用该模块的模块
filename: '/path/to/example.js', // 模块文件名
loaded: false, //是否加载完成
children: // 该模块要用到的其他模块
[ { id: '/path/to/node_modules/jquery/dist/jquery.js',
exports: [Function],
parent: [Circular],
filename: '/path/to/node_modules/jquery/dist/jquery.js',
loaded: true,
children: [],
paths: [Object] } ],
paths:
[ '/home/user/deleted/node_modules',
'/home/user/node_modules',
'/home/node_modules',
'/node_modules' ]
}
如果在命令行下调用某个模块,比如node something.js
那么module.parent
就是undefined
。
如果实在脚本之中调用,比如require("./something.js")
,那么module.parent
就是调用它的模块。
利用这一点,可以判断当前模块是否为入口脚本。
if(!module.parent) {
// ran with `node something.js`
app.listen(8088,function(){
console.log("app listeing on port 8088");
})
}else{
// used with `require("./someting.js")`
module.exports = app;
}
2.1 module.exports
属性
module.exports
属性表示当前模块对外输出的接口,其他文件加载该模块,实际上就是读取module.exports
变量。
var EventEmitter = require('events').EventEmitter;
moudle.exports new EventEmitter();
setTimeout(funciton(){
moudle.exports.emote('ready');
},1000)
上面模块会在加载后一秒以后,发出ready时间,其他文件监听该事件,可以写成下面这样。
var e = require('./e');
e.on('ready',function(){
console.log('module e is ready');
})
2.2 exports变量
为了方便,Node为每个模块提供了一个exports变量,指向module.exeports
。 在这等同于在每个模块头部,有一行这样的命令。
var exports = module.exports;
造成的结果是,在对外输出模块接口时,可以向exports对象添加方法。
exports.area = function(r){
return Math.PI * r * r;
}
exports.circumference = function (r) {
return 2 * Math.PI * r;
};
注意,不能直接将exports变量指向一个值,因为这样等于切断了exports
与module.exports
的联系。
exports = function(x){console.log(x)};
上面这样的写法是无效的。
因为exports
不能在指向module.exports
了。
下面的写法也是无效的。
exports.hello = function(){
return 'hello';
};
module.exports = 'Hello world';
上面代码中,hello
函数是无法对外输出的,因为module.exports
被重新赋值了。
如果你觉得,exports
与module.exports
之间的区别很难分清,一个简单的处理方法,就是放弃使用exports
,只使用module.exports
。