Skip to content

Commit

Permalink
文件压缩
Browse files Browse the repository at this point in the history
  • Loading branch information
[email protected] committed Feb 25, 2024
1 parent 5adb3f3 commit e8102d0
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 7 deletions.
59 changes: 52 additions & 7 deletions servers/http-last-modified.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import url from 'url'
import path from 'path'
import fs from 'fs'
import mime from 'mime'
import zlib from 'zlib'

const __filename = url.fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
Expand All @@ -24,21 +25,65 @@ const server = http.createServer((req, res) => {
const stats = fs.statSync(filePath);
const timeStamp = req.headers['if-modified-since'];

const mimeType = mime.getType(ext);
console.log("🚀 ~ server ~ mimeType:", mimeType)
const responseHeaders = {
'Content-Type': mimeType,
'Cache-Control': 'max-age=86400', // 缓存一天
'Last-Modified': stats.mtimeMs,
}

const acceptEncoding = req.headers['accept-encoding'];
const compress = acceptEncoding && /^(text|application)\//.test(mimeType)

if (compress) {
// 返回客户端支持的一种压缩方式
acceptEncoding.split(/\s*,\s*/).some((encoding) => {
if (encoding === 'gzip') {
responseHeaders['Content-Encoding'] = 'gzip';
return true;
}
if (encoding === 'deflate') {
responseHeaders['Content-Encoding'] = 'deflate';
return true;
}
if (encoding === 'br') {
responseHeaders['Content-Encoding'] = 'br';
return true;
}
return false;
});
}

const compressionEncoding = responseHeaders['Content-Encoding']; // 获取选中的压缩方式

let status = 200;

if (timeStamp && Number(timeStamp) === stats.mtimeMs) {
// 如果timeStamp和stats.mtimeMS相等,说明文件内容没有修改
status = 304
}
res.writeHead(status, {
'Content-Type': mime.getType(ext),
'Cache-Control': 'max-age=86400', // 缓存一天
'last-modified': stats.mtimeMs,
});

res.writeHead(status, responseHeaders);


if (status === 200) {
const fileStream = fs.createReadStream(filePath)
fileStream.pipe(res)
const fileStream = fs.createReadStream(filePath);
if (compress && compressionEncoding) {
let comp;

// 使用指定的压缩方式压缩文件
if (compressionEncoding === 'gzip') {
comp = zlib.createGzip();
} else if (compressionEncoding === 'deflate') {
comp = zlib.createDeflate();
} else {
comp = zlib.createBrotliCompress();
}
fileStream.pipe(comp).pipe(res);
} else {
fileStream.pipe(res);
}
} else {
res.end() // 如果状态码不是200,则不需要返回body
}
Expand Down
Loading

0 comments on commit e8102d0

Please sign in to comment.