1、引入http模块
let http = require(‘http’)
2、创建web服务 返回http对象
let app = http.createServer((req,res)=>{
req 请求体 浏览器->服务器
req.url 地址 提取地址栏数据req.on('data') 提取非地址栏数据 所有的http[s]都会触发end事件 req.on('end') res 响应 服务器->浏览器 res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});响应头设置 res.write(字符/数据<string><buffer>) 返回数据 res.end() 结束响应 必须 })
3、监听
app.listen(端口,[地址],[回调])
案例:
et http = require('http')//commonJs模块化输入模块的方法
//创建web服务 返回http对象
// http.createServer(函数) 创建一个server对象,未来有人访问时,函数就会调用,返回server对象
let app = http.createServer(()=>{
console.log('有人访问了,就调用')
})
// 监听服务器
// app.listen(端口,主机地址,成功回调)
app.listen('3000','127.0.0.1',()=>{
console.log("服务器跑起来了")
})
请求体,响应体所携带的api
let http = require('http')//commonJs模块化输入模块的方法
//创建web服务 返回http对象
// http.createServer(函数) 创建一个server对象,未来有人访问时,函数就会调用,返回server对象
let app = http.createServer((req,res)=>{
console.log('有人访问了,就调用')
console.log('抓取地址栏信息',req.url)
//响应
// res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
//返回是字符
res.write(`
<html>
<head>
<meta charset="utf-8">
<title>第一个node服务器返回的网页</title>
</head>
<body>
<h1>后烧肉</h1>
</body>
</html>
`);
res.end();//结束响应
})
// 监听服务器
// app.listen(端口,主机地址,成功回调)
app.listen('3000','127.0.0.1',()=>{
console.log("服务器跑起来了")
})
fs模块_磁盘文件的操作
1、读取:
fs.readFile(‘文件路径’,[编码方式],(err,data)=>{})
err :错误,null没有错误 data :数据,buffer流
变量 = fs.readFileSync(‘文件路径’)
//读取静态资源 file system 模块
let fs = require('fs');
//文件操作 的结果 都是 "异步" 的
//读
// fs.readFile('地址',[编码格式默认是流],回调(失败,数据))
/* fs.readFile('./www/index.html',(err,data)=>{
// fs.readFile('./www/index.html','utf-8',(err,data)=>{
// console.log(err);//null 没有错误
console.log(data);//数据 流
}) */
// let data = fs.readFileSync('./www/index.html');
// console.log(data);
//同步写异步的写法, 校验他的错误时
try{
let data = fs.readFileSync('./www/index1.html');
console.log(data);
}catch(e){}
console.log('后续代码')
// try ...catch
//原生js try..catch 用法,用来应急
/* try{
//测试3000行代码
console.log(1);
doc.a.b();
console.log(2);
}catch(e){
// 处理错误,保证不挂起
// console.log('catch',e)
}
console.log(3); */
//更名
// fs.rename('改前','改后',回调)
// fs.rename('./www/default.html','./www/index.html',err=>console.log(err))
fs.rename('./www/index.html','./wwww/index2.html',err=>console.log(err))
// let 正确结果 = fs.renameSync('改前','改后')
// let result = fs.renameSync('./www/index.html','./www/default.html');
// console.log(result);
//删除
// fs.unlinkSync('./www/a.txt');
try … catch 用法,用来应急的
try ...catch:当不确定哪一个阶段出错,可以放在try后面出错后用catch来处理,保证正确的能运行
try{
要排错的代码
}catch{
处理错误,保证不挂起
}