web开发中的压缩、range范围请求
2018-01-06 本文已影响0人
JTR354
压缩
//定义要压缩的文件类型
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)
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)