程序员和他的女神们日总结我爱编程

node.js创建模块

2017-06-07  本文已影响23人  张鸽

require方法接受以下几种参数的传递:

由于Node.js中存在4类模块(原生模块和3种文件模块),尽管require方法极其简单,但是内部的加载却是十分复杂的,其加载优先级也各自不同。


Paste_Image.png

加载优先级:
文件模块缓存区>原生模块>原生模块缓存区>文件模块

创建模块

在Node.js中,定义一个模块十分方便。我们以计算圆形的面积和周长两个方法为例,来表现Node.js中模块的定义方式。

var PI = Math.PI;
exports.area = function (r) {
    return PI * r * r;
};
exports.circumference = function (r) {
    return 2 * PI * r;
};

将这个文件存为circle.js,并新建一个app.js文件,并写入以下代码:

var circle = require('./circle.js');
console.log( 'The area of a circle of radius 4 is ' + circle.area(4));
console.log( 'The circumference of a circle of radius 4 is ' + circle.circumference(4));

可以看到模块调用也十分方便,只需要require需要调用的文件即可。
在require了这个文件之后,定义在exports对象上的方法便可以随意调用。
当然也可以把一个对象封装在模块中
例如:

//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。

上一篇 下一篇

猜你喜欢

热点阅读