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.xxx和module.exports的方式暴露接口本质是一样的。
其实在node.js的模块机制中,exports= module.exports = {};也就是说在开始是exports是module.exports的一个应用。当我们在其他地方使用require命令导入时,返回的是module.exports对象。
所以在上面第一种中,使用require('./hello')返回的是module.exports对象,该对象有一个world属性(也就是hello.js中的函数)
在上面第二种中,使用require('./hello')返回的是module.exports对象,该对象没有什么world属性,它就是函数对象。
0 0
- Node.js中的模块管理
- Node.js中的模块
- Node.js 中的模块
- Node.js中的模块
- node.js的模块管理
- Node.js中的OS模块
- Node.js中的URL模块
- Node.js中的Path模块
- Node.js中的Console模块
- Node.js中的DNS模块
- Node.js中的Net模块
- Node.js中的Assert模块
- Node.js中的HTTP模块
- Node.js中的模块机制
- node.js中的加密模块
- node.js中的fs模块
- log4js-Node.js中的日志管理模块使用与封装
- Node.js中的Query String模块
- Python-2 Python小程序
- 疯狂JAVA讲义学习笔记2——理解面向对象
- js 提示
- 我的2016个人总结
- Linux中的静态库、动态库
- Node.js中的模块管理
- (牛客)拜访(动态规划)
- asp分页查询,判断单选按钮传值,session无效。下一页没有效果?
- 高分求助:一个提示“EOF和BOF为真”的问题,一会正常一会不正常,望解决...
- C语言中one_three编写
- 竟然会无法修改label字体大小!!!
- hdu1091 - A+B for Input-Output Practice (III)
- Node.js的包管理工具npm学习
- 和我一起学Hadoop(一):Linux的准备配置之hostname、静态IP配置、SSH免密登陆登陆