MCPcopy Create free account
hub / github.com/Silentely/eSIM-Tools / compressFile

Function compressFile

scripts/compress.js:36–109  ·  view source on GitHub ↗
(filePath)

Source from the content-addressed store, hash-verified

34
35// 压缩单个文件
36async function compressFile(filePath) {
37 try {
38 const content = fs.readFileSync(filePath);
39 const ext = path.extname(filePath);
40
41 // 只压缩特定类型的文件
42 if (!compressibleExtensions.includes(ext)) {
43 return null;
44 }
45
46 // Skip small files (compression not worth it)
47 if (content.length < MIN_COMPRESS_SIZE) {
48 return null;
49 }
50
51 const fileName = path.basename(filePath);
52 const dir = path.dirname(filePath);
53 const fileStat = fs.statSync(filePath);
54
55 // Check cache - skip if already compressed and source hasn't changed
56 const cacheKey = filePath;
57 if (compressionCache.has(cacheKey)) {
58 const cached = compressionCache.get(cacheKey);
59 if (cached.mtime >= fileStat.mtimeMs) {
60 return null; // Already compressed
61 }
62 }
63
64 // Gzip压缩
65 const gzipPath = path.join(dir, `${fileName}.gz`);
66 const gzipped = await gzip(content, compressionOptions.gzip);
67
68 // Only write if compression achieved meaningful reduction
69 const compressionRatio = (content.length - gzipped.length) / content.length;
70 if (compressionRatio > 0.1) { // At least 10% reduction
71 fs.writeFileSync(gzipPath, gzipped);
72 } else {
73 return null; // Skip if compression is not effective
74 }
75
76 // Brotli压缩(如果支持)
77 let brotliSize = 0;
78 try {
79 const brotlied = await brotliCompress(content, compressionOptions.brotli);
80 const brotliPath = path.join(dir, `${fileName}.br`);
81
82 // Only write if brotli is smaller than gzip
83 if (brotlied.length < gzipped.length) {
84 fs.writeFileSync(brotliPath, brotlied);
85 brotliSize = brotlied.length;
86 }
87 } catch (error) {
88 BuildLogger.log(`Brotli压缩失败 ${fileName}:`, error.message);
89 }
90
91 const originalSize = content.length;
92 const gzipSize = gzipped.length;
93 const compressionRatioPercent = (compressionRatio * 100).toFixed(1);

Callers 1

scanDirectoryFunction · 0.85

Calls 5

hasMethod · 0.80
getMethod · 0.45
logMethod · 0.45
setMethod · 0.45
errorMethod · 0.45

Tested by

no test coverage detected