Stream
const fs = require('fs')
//讀取流
const rs = fs.createReadStream('./01.png')
//寫入流
const ws = fs.createWriteStream('./02.png')
//把讀取和寫入對(duì)接 目的是復(fù)制01的圖片 取名為02
rs.pipe(ws)
http web服務(wù)模塊
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:用于創(chuàng)建web服務(wù)的模塊
//創(chuàng)建一個(gè)http服務(wù)器
const http = require('http')
//讀取文件服務(wù)器
const server = http.createServer((request,response)=>{
//打印原型鏈 request和response都是steam
// console.log('request',getPrototypeChain(request));
// console.log('response',getPrototypeChain(response));
const {url,method,headers} = request
//是首頁(yè)并且是get請(qǐng)求
if(url === '/' && method === 'GET'){
//讀取html 首頁(yè)
fs.readFile('index.html',(err,data) => {
if(err){
//設(shè)置一組
response.writeHead(500,{
'Content-Type':'text/plain;charset=utf-8'
})
response.end('服務(wù)器錯(cuò)誤')
}
response.statusCode = 200
//設(shè)置一個(gè)
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{
//找不到頁(yè)面
response.statusCode = 404
response.setHeader('Content-Type','text/plain;charset=utf-8')
response.end('404頁(yè)面沒有找到')
}
// response.end('a response')
})
server.listen(3000);
//node api.js運(yùn)行完畢 在瀏覽器輸入http://localhost:3000/ 查看