### 作业
1. 静态文件服务器
```js
const http = await import('http')
const fs = await import('fs')
const proc = ((req,res)=>{
let file = `./public${req.url}`
let FilePath = file.replace('favicon.ico',"")
// 检查文件是否存在
if (!fs.existsSync(FilePath)) {
res.end('404')
console.log('文件未找到');
return
}
else{
// 读取文件
fs.readFile(FilePath,(err,data)=>{
// 根据文件拓展名设置Content-Type
const ext = FilePath.substring(FilePath.lastIndexOf('.'))
console.log(ext);
switch(ext){
case '.html':
return 'text.html'
case '.css':
return 'text.css'
case '.js':
return 'text.js'
default:
break;
}
// 返回文件内容
res.end(data)
})
}
})
let app = http.createServer(proc)
app.listen(8080)
```
2. 日志记录服务器
```js
const http = await import('http')
const fs = await import('fs')
// 时间戳
const date = Date.now()
let proc = (req,res)=>{
//请求方法
let me = req.method
//请求路径
const path = req.url
//客户端IP地址
const ip = req.headers.host
// 日志文件的格式为:[时间戳] - [请求方法] - [请求路径] - [客户端IP]。
const log = `[${date}]-[${me}]-[${path}]-[${ip}]`
fs.appendFile('./server.log',log,'utf8',(err)=>{
if (err) {
console.log('日志添加失败');
}
else{
fs.readFile('./index.html',(err,data)=>{
if (err) {
console.log('文件没找到');
}
else{
res.end(data)
}
})
}
})
}
let app = http.createServer(proc)
app.listen(5000)
```
3. 图片查看器
```js
const fs = await import('fs')
const http = await import('http')
let proc = function(req,res){
// 请求路径【用户通过访问/view?filename=】
let FilePath = `./images/${req.url.split('?')[1]?.split('=')[1]}`
// 请求的图片存在,返回图片内容
if (fs.existsSync(FilePath)) {
// 读取文件
fs.readFile(FilePath,(err,data)=>{
if (err) {
console.log('读取失败');
}
else{
// 根据文件扩展名判断
const ext = FilePath.substring(FilePath.lastIndexOf('.'))
let contentType = '';
switch (ext) {
case 'jpeg':
contentType = 'image/jpeg';
break;
case 'png':
contentType = 'image/png';
break;
case 'jpg':
contentType = 'image/jpg';
break;
default:
break;
}
// 返回图片内容
res.end(data)
}
})
}
else{
res.end('404')
}
}
let app = http.createServer(proc)
app.listen(4000)
```
4. 文件搜索服务
```js
const http = await import('http')
const fs = await import('fs')
let proc = function(req,res){
let keywords = req.url.split('?')[1]?.split('=')[1]
let FilePath = `.${req.url.split('?')[0]}`; // 获取路径部分
FilePath = FilePath.replace('/search',"")
console.log(FilePath);
// 读取指定目录中的文件列表
fs.readdir(FilePath,(err,files)=>{
if (!err) {
// 遍历文件列表
const SearchFile = files.filter(x=>x.includes(keywords))
// 返回JSON
res.end(JSON.stringify({files:SearchFile}))
}
else{
res.end('404')
}
})
}
let app = http.createServer(proc)
app.listen(8000)
// http://localhost:8000/search?query=example 这样访问
```
5. 简单Web服务
```js
const http = await import('http')
const fs = await import('fs')
const proc = function(req,res){
// 如果路径是 /,则将其视为目录请求
if (req.url == '/') {
// 依次搜索
// 定义顺序
const def = ['index.html','default.html']
// 读取文件内容
switch (true) {
// 检查index
case fs.existsSync(def[0]):
// 读取文件
fs.readFile(def[0],(err,data)=>{
if(err){res.end('404')}
else{
res.end(data)
}
})
break;
case fs.existsSync(def[1]):
fs.readFile(def[1],(err,data)=>{
if(err){res.end('404')}
else{
res.end(data)
}
})
break;
default:
break;
}
}
else{
res.end('404')
}
}
const app = http.createServer(proc)
app.listen(8080)
```
#### Stream(流)
1. 数据按顺序依次流动,不能随机访问。
2. 读写数据:从文件、网络等读取或写入数据。
### Node.js HTTP 服务器和文件服务器开发
1. HTTP 服务器开发
- `request` 对象封装了 HTTP 请求信息。
- `response` 对象用于构建 HTTP 响应并返回给客户端。
2.
```js
// 导入http模块
const http = await import('http')
let proc = function(request,response){
// 将http响应的HTMLneir写进response
console.log(request.url);
response.end('88')
}
let app = http.createServer(proc)
app.listen(8080)
```
- 协议://主机地址:端口号/路径?keywords = 888【】
- 所谓的Web服务器,在不同的语境中有不同含义:它有可能是指如nginx、apache这样托管类的程序,也可能指程序员开发的具有Web服务功能的程序,也有可能是指承载Web程序的物理服务器
- 现代计算机系统,端口号的范围:0 ~ 65535【其中0 ~ 1000是系统保留号】【后面的由用户自己分配】
- 常见的端口号:3306(mysql、MariaDb)、80(web)、22(ssh)、23(ftp)、3389(windows远程桌面)、5432(PostgreSql)
3. 文件服务器开发
- 文件服务器:通过解析 request.url 中的路径,将本地文件内容发送给客户端。
- url 模块:用于解析 URL,提取路径、查询参数等。
- path 模块:用于处理文件路径,确保跨平台兼容性。
- fs 模块:用于读取本地文件系统中的文件。
4. 使用页面html
```js
const http = await import('http')
const fs = await import('fs')
const app = http.createServer(function(req,res){
fs.readFile('index.html','utf8',(err,data)=>{
if (err) {
console.log(err);
}
else{
res.end(data)
}
})
})
app.listen(5000)
```