使用Node编写应用程序主要就是在使用:
在Node中的JavaScript还有一个重要的概念,模块系统。
require
语法:
var 自定义变量名 = require('模块')
作用:
exports
导出接口对象exports
exports
接口对象中就可以了导出多个成员(必须在对象中):
```javascript
exports.a = 123;
exports.b = function(){
console.log('bbb')
};
exports.c = {
foo:"bar"
};
exports.d = 'hello';
```
导出单个成员(拿到的就是函数,字符串):
```javascript
module.exports = 'hello';
```
以下情况会覆盖:
```javascript
module.exports = 'hello';
//后者会覆盖前者
module.exports = function add(x,y) {
return x+y;
}
```
也可以通过以下方法来导出多个成员:
```javascript
module.exports = {
foo = 'hello',
add:function(){
return x+y;
}
};
```
exports和module.exports
的一个引用:
console.log(exports === module.exports); //true
exports.foo = 'bar';
//等价于
module.exports.foo = 'bar';
当给exports重新赋值后,exports!= module.exports.
最终return的是module.exports,无论exports中的成员是什么都没用。
真正去使用的时候:
导出单个成员:exports.xxx = xxx;
导出多个成员:module.exports 或者 modeule.exports = {};
// 引用服务
var http = require('http');
var fs = require('fs');
// 引用模板
var template = require('art-template');
// 创建服务
var server = http.createServer();
// 公共路径
var wwwDir = 'D:/app/www';
server.on('request', function (req, res) {
var url = req.url;
// 读取文件
fs.readFile('./template-apche.html', function (err, data) {
if (err) {
return res.end('404 Not Found');
}
fs.readdir(wwwDir, function (err, files) {
if (err) {
return res.end('Can not find www Dir.')
}
// 使用模板引擎解析替换data中的模板字符串
// 去xmpTempleteList.html中编写模板语法
var htmlStr = template.render(data.toString(), {
title: 'D:/app/www/ 的索引',
files:files
});
// 发送响应数据
res.end(htmlStr);
})
})
});
server.listen(3000, function () {
console.log('running....');
})
module.exports.xxx = xxx
的方式
但是每次写太多了就很麻烦,所以Node为了简化代码,就在每一个模块中都提供了一个成员叫exports
exports === module.exports
结果为true,所以完全可以exports.xxx = xxx
当一个模块需要导出单个成员的时候必须使用module.exports = xxx
的方式,=,使用exports = xxx
不管用,因为每个模块最终return的是module.exports,而exports只是module.exports的一个引用,所以exports
即使重新赋值,也不会影响module.exports
。
有一种赋值方式比较特殊:exports = module.exports
这个用来新建立引用关系的。我正在参与2023腾讯技术创作特训营第三期有奖征文,组队打卡瓜分大奖!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。