web开发中的压缩、range范围请求

压缩

//定义要压缩的文件类型
compress: /\.(js|css|html|md)/
//压缩函数引用zlib
const {createGzip,createDeflate} = require('zlib')
module.exports = (rs ,req ,res)=>{
   const acceptEncoding = req.headers['accept-encoding']
   if(!acceptEncoding || !acceptEncoding.match(/\bgzip|deflate\b/)){
       return rs
   }else if(acceptEncoding.match(/\bgzip\b/)){
       res.setHeader('Content-Encoding','gzip')
       return rs.pipe(createGzip())
   }else if(acceptEncoding.match(/\bdeflate\b/)){
       res.setHeader('Content-Encoding','deflate')
       return rs.pipe(createDeflate())
   }
}
//将压缩的文件流导入res
const press = require('../handle/compress')
let rs = fs.createReadStream(filePath)
if (filePath.match(compress)) {
   rs = press(rs, req, res)
}
rs.pipe(res)
  • Web服务器处理HTTP压缩之gzip、deflate压缩
  • 【Web优化】Yslow优化法则(四)启用Gzip压缩

range范围请求

  • range:bytes=[start]-[end]
  • Accept-Ranges:bytes
  • Content-Range:bytes start-end/total
//定义range函数
module.exports = (totalSize, req, res) => {
    const range = req.headers['range']
    if (!range) {
        return {code: 200}
    }

    const sizes = range.match(/bytes=(\d*)-(\d*)/)

    const end = sizes[2] || totalSize - 1
    const start = sizes[1] || totalSize - end

    if (start - end < 0 || start < 0 || end > totalSize) {
        return {code: 200}
    }
    res.setHeader('Accept-Ranges', 'bytes')
    res.setHeader('Content-Range', `bytes ${start}-${end}/${totalSize}`)
    res.setHeader('Content-Length', end - start)

    return {
        code: 206,
        start: parseInt(start),
        end: parseInt(end)
    }

}
//设置206并导出至res
const range = require('../handle/range')
const {code,start,end} = range(stats.size,req,res)
switch (code){
    case 200:{
        rs = fs.createReadStream(filePath)
        break
    }
    case 416:{
        rs = fs.createReadStream(filePath)
        break
    }
    case 206:{
        rs = fs.createReadStream(filePath,{start,end})
        break
    }
    default:{
        rs = fs.createReadStream(filePath)
    }
}
rs.pipe(res)
  • 实践HTTP206状态:部分内容和范围请求
  • RFC7233 HTTP范围请求(Range Requests)
  • HTTP请求范围-MDN

你可能感兴趣的:(web开发中的压缩、range范围请求)