1.核心模块
//页面判断器
const http =require('http')
// 1.创建 Server
var server = http.createServer()
// 2.监听request 请求事件 设置请求处理函数
server.on('request',(req,res)=>{
// console.log('收到请求了,请求路径是'+req.url);
// // res.write('hello')
// res.end('hello world')
// res.end('hello world')
var url=req.url
console.log(url);
if(url === '/'){
res.end('index page')
}else if(url ==='/login'){
res.end('login page')
}else if(url === '/products'){
var products=[{
name:'苹果',
price:8888
},
{
name:'梨子',
price:8888
},
{
name:'香蕉',
price:8888
},
{
name:'葡萄',
price:8888
},
{
name:'樱桃',
price:8888
},
]
// for (let i = 0; i < products.length; i++) {
// res.write(JSON.stringify(products[i].name,products[i].price+"<br/>") )
// res.end()
// }
// res.end(JSON.stringify(products[i].name,products[i].price+"<br/>") )
res.end(JSON.stringify(products))
}
else{
res.end('404 Not Found')
}
})
// 3.绑定端口号
server.listen(3000,()=>{
console.log('服务器启动成功,可以访问了....');
})
//文件模块
var fs = require('fs')
//
require 是一个方法 加载文件中的方法
它的左右就是用来加载模块的
在node中,模块有三种
具名的核心模块,例如 fs、http
用户自己编写的文件模块
require 读取
exports 输出
相对路径必须加 ./ (不能省略)不然会被当作核心模块
node中没有全局作用域,只有模块作用域
外部访问不到内部
内部也访问不到外部
模块作用域 就是如何让模块与模块之间进行通信
加载文件模块的目的不仅仅是为了简简单单执行里面的代码,更重要的还是使用里面的某个方法
require 方法有两个作用
1.加载文件模块并执行里面的代码
2.拿到被加载文件模块导出的接口对象
在每个文件都提供一个对象 叫做 exports
exports默认是一个空对象 把 exports .add()=
需要做的就是吧所有需要被外部访问的成员挂载到这个exports对象中
res.end只能支持两种参数,要么字符串,要么Buffer
res.send可以支持多种参数,比如可以传json对象,Buffer,String,Array
The body parameter can be a Buffer object, a String, an object, or an Array. For example:
res.send()参数可传可不传
Content-Type 链接http://tool.oschina.nethttp://tool.oschina.net
当使用 fs模块时候
引用本地链接 c:\des\
需要将斜号反过来
c:/des/
模板引擎
注意:在浏览器中需要引用lib、template-web.js文件
<script src="node_modules/art-template/lib/template-web.js"></script>
强调 :模板引擎不关心你的字符串内容,只关心自己能认识的模板标记语法,例如{{}}
模板引擎被称之为mustache 语法 ,八字胡