优化静态资源

Node.js————优化静态资源

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const http = require('http')
const path = require('path')
const fs = require('fs')
//引入映射表,根据文件后缀获取对应的类型
const mine = require('./mime.json')
http.createServer((request, response) => {
    fs.readFile(path.join(__dirname, request.url), (err, fileContent) => {
        if(err){
            //没有找到对应的文件
            response.writeHead(404, {
                'content-Type':'text/plain; charset=utf8'
            })
            response.end("你访问的页面正在大西洋漂着...")
        }else{
            let dtype = 'text/html'
            //获取求情文件的后缀
            let ext = path.extname(request.url)
            //如果请求的文件后缀合理,就获取到标准的响应格式
            if(mine[ext]){
                dtype = mine[ext]
            }
            //如果响应的内容是文本,就设置成utf8编码
            if(dtype.startsWith('text')){
                dtype += '; charset=utf8'
            }
            //设置响应头信息
            response.writeHead(200, {
                'content-Type':dtype
            })
            response.end(fileContent)
        }
    })
}).listen(3000, () => {
    console.log('running...')
})


-->