Node.js中的模块管理

来源:互联网 发布:sql load data 编辑:程序博客网 时间:2024/06/05 07:20

1.Node.js中的模块

一个Node.js文件就是一个模块,这个文件可能是JavaScript代码、JSON 或者编译过的C/C++ 扩展。且在该文件中需要使用exports和module.exports将模块中的函数和变量导出。然后在要使用模块的文件中使用require('./filename')来引入模块。

 

2.举例说明

1)使用exports.xxx的方式对外暴露功能

//编写hello.js模块文件,对外暴露方法

exports.world =function() {    console.log('Hello World');}

node.js文件中使用该模块:

var hello = require('./hello');hello.world();

2)使用module.exports的方式对外暴露功能

//编写hello.js模块文件,对外暴露方法

function Hello() {    var name;    this.setName= function(thyName) {        name = thyName;    };    this.sayHello= function() {        console.log('Hello' + name);    };};module.exports = Hello;

node.js文件中使用该模块:

var Hello = require('./hello');hello = new Hello();hello.setName('BYVoid');hello.sayHello();

备注:这里需要注意的是其实使用exports.xxxmodule.exports的方式暴露接口本质是一样的。

其实在node.js的模块机制中,exports= module.exports = {};也就是说在开始是exportsmodule.exports的一个应用。当我们在其他地方使用require命令导入时,返回的是module.exports对象。

所以在上面第一种中,使用require('./hello')返回的是module.exports对象,该对象有一个world属性(也就是hello.js中的函数)

在上面第二种中,使用require('./hello')返回的是module.exports对象,该对象没有什么world属性,它就是函数对象。



0 0
原创粉丝点击