Node.js入门(下)
2019-11-18 本文已影响0人
key君
Stream
const fs = require('fs')
//读取流
const rs = fs.createReadStream('./01.png')
//写入流
const ws = fs.createWriteStream('./02.png')
//把读取和写入对接 目的是复制01的图片 取名为02
rs.pipe(ws)
http web服务模块
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Hello Node</h1>
<img src="01.png" alt=""/>
</body>
</html>
api.js
//文件读取
const fs = require('fs')
// http:用于创建web服务的模块
//创建一个http服务器
const http = require('http')
//读取文件服务器
const server = http.createServer((request,response)=>{
//打印原型链 request和response都是steam
// console.log('request',getPrototypeChain(request));
// console.log('response',getPrototypeChain(response));
const {url,method,headers} = request
//是首页并且是get请求
if(url === '/' && method === 'GET'){
//读取html 首页
fs.readFile('index.html',(err,data) => {
if(err){
//设置一组
response.writeHead(500,{
'Content-Type':'text/plain;charset=utf-8'
})
response.end('服务器错误')
}
response.statusCode = 200
//设置一个
response.setHeader('Content-Type','text/html')
response.end(data)
})
}else if(url === '/users' && method === 'GET'){
//读取/users json
response.writeHead(200,{
'Content-Type':'application/json'
})
response.end(JSON.stringify([{name: 'laowang'}]))
}else if(method === 'GET' && headers.accept.indexOf('image/*') !== -1){
//读取图片
fs.createReadStream('.'+url).pipe(response)
}else{
//找不到页面
response.statusCode = 404
response.setHeader('Content-Type','text/plain;charset=utf-8')
response.end('404页面没有找到')
}
// response.end('a response')
})
server.listen(3000);
//node api.js运行完毕 在浏览器输入http://localhost:3000/ 查看