当前位置: 首页 > news >正文

Http模块及练习

### 作业

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)

```

相关文章:

  • C++单例模板类,继承及使用
  • C语言宏定义的底层应用
  • 【SpringMVC】概述 SSM:Spring + SpringMVC + Mybats
  • 在CentOS安装Docker
  • Redis常用数据类型及其应用案例
  • 机器学习数学基础:30.Pearson相关系数及t检验教程
  • 信息安全实战04_ECC椭圆曲线加密算法原理详解
  • 蓝桥杯试题:区间次方和(前缀和)
  • Gin从入门到精通 (四)请求参数
  • 网络运维学习笔记 022 HCIA-Datacom新增知识点03园区网典型组网架构及案例实战
  • 第一届网谷杯
  • 力扣每日一题【算法学习day.133】
  • 敏捷开发08:如何高效开每日站会(Daily Stand-up Meeting)
  • LEARNING ON LARGE-SCALE TEXT-ATTRIBUTED GRAPHS VIA VARIATIONAL INFERENCE
  • Go语言中使用viper绑定结构体和yaml文件信息时,标签的使用
  • NIO-Reactor模型梳理与demo实现
  • Linux 第三次脚本作业
  • 如何使用智能指针来管理动态分配的内存
  • 函数中的形参和实参(吐槽)
  • R 语言科研绘图 --- 散点图-汇总
  • 是否进行了及时有效处置?伤者情况如何?辽阳市相关负责人就饭店火灾事故答问
  • 阿迪达斯一季度营收增近13%,称美国加征关税对业绩带来不确定性
  • 北大深圳研究生院成立科学智能学院:培养交叉复合型人才
  • 上海74岁老人宜春旅游时救起落水儿童,“小孩在挣扎容不得多想”
  • 王毅会见俄罗斯外长拉夫罗夫
  • 报告显示2024年全球军费开支增幅达冷战后最大