一、art-template模板文件的使用
1.浏览器中直接使用
<script src="lib/template-web.js"></script>
<script id="tpl-user" type="text/html">
{{if user}}
<h2>{{user.name}}</h2>
{{/if}}
</script>
2.node服务中使用
(1)安装 npm install --save art-template
(2)app.js中使用
//加载art-template
var template = require('art-template');
var http = require('http');
var fs = require('fs');
var url = require('url');
var contents = [
{
name:lisa,
age:18
},
];
//创建server
http.createServer(function(req,res){
var parseObj=url.parse(req.url,true);
var pathname=parseObj.pathname;
if(pathname==='/'){
fs.readFile('./comments',function(error,data){
if(error){ return res.end('404 not found'); }
var htmlStr = template.render(data.toString(),{
contents:contents
});
res.end(htmlStr );
})
}
if(pathname==='pinglun'){
var age=17;
var content=parseObj.query;
content.age=age;
contents.unshift(content);
res.statusCode=302;//设置重定向
res.setHeader('location','/');
res.end();
}
}).listen(3000,function(){'服务启动了'});
comments.html中代码块
{{each contents}}
<li>姓名:{{$value.name}}年龄{{$value.age}}</li>
{{/each}}
二、jquery中each和JavaScript中forEach的区别
1.js中forEach是js5中Array数组对象中的方法
语法是array.forEach(function(element,index){});
2.jquery中$.each()是全局函数,可以遍历dom元素、对象和数组,$.each(arrays,function(index,item){});
dom对象.each(function(index,item){})但不可以遍历数组,可以将伪数组转成数组Array.slice.call(伪数组);
三、node模块系统
1、核心模块,直接用require('模块名')加载引用即可;
2、第三方模块;先要使用npm安装,然后再用require加载,安装命令是npm install -S 模块名
3、用户自定义模块;用相对路径加载
4、node中,没有全局作用域变量,只有模块作用域,每个模块都对外提供一个接口exports,当模块中的变量需要对外暴露时,将此变量挂在到exports上例如var name='xiaoli' ;exports.name=name;
返回单个对象时使用module.exports=对象;返回多个变量时可以使用exports.对象名=对象;也可以用module.exports={对象名:对象};
5.exports和module.exports的区别
每个模块中都有一个 module 对象
module 对象中有一个 exports 对象
我们可以把需要导出的成员都挂载到 module.exports 接口对象中
也就是:moudle.exports.xxx = xxx 的方式
但是每次都 moudle.exports.xxx = xxx 很麻烦,点儿的太多了
所以 Node 为了你方便,同时在每一个模块中都提供了一个成员叫:exports
exports === module.exports 结果为 trues
所以对于:moudle.exports.xxx = xxx 的方式 完全可以:expots.xxx = xxx
当一个模块需要导出单个成员的时候,这个时候必须使用:module.exports = xxx 的方式
不要使用 exports = xxx 不管用
因为每个模块最终向外 return 的是 module.exports
而 exports 只是 module.exports 的一个引用
所以即便你为 exports = xx 重新赋值,也不会影响 module.exports
但是有一种赋值方式比较特殊:exports = module.exports 这个用来重新建立引用关系的
6、require加载规则
先找到当前文件所处目录中的 node_modules 目录
然后根据以下方式找到文件中的 main 属性
node_modules/art-template
node_modules/art-template/package.json 文件
node_modules/art-template/package.json 文件中的 main 属性
main 属性中就记录了 art-template 的入口模块
然后加载使用这个第三方包,但是实际上最终加载的还是文件
如果 package.json 文件不存在或者 main 指定的入口模块是也没有
则 node 会自动找该目录下的 index.js,也就是说 index.js 会作为一个默认备选项
如果以上所有任何一个条件都不成立,则会进入上一级目录中的 node_modules 目录查找
如果上一级还没有,则继续往上上一级查找
如果直到当前磁盘根目录还找不到,最后报错: can not find module xxx