20 lines
1.4 KiB
JavaScript
20 lines
1.4 KiB
JavaScript
'use strict';
|
|
// 最小 ZIP 读取器(xlsx 用),只支持 stored/deflate。返回 [{name,data:Buffer}],按中央目录顺序。
|
|
const zlib=require('node:zlib');
|
|
function unzip(buffer){
|
|
let eocd=-1;for(let i=buffer.length-22;i>=Math.max(0,buffer.length-65557);i--)if(buffer.readUInt32LE(i)===0x06054b50){eocd=i;break;}
|
|
if(eocd<0)throw new Error('不是有效的 ZIP 文件');
|
|
const count=buffer.readUInt16LE(eocd+10);let offset=buffer.readUInt32LE(eocd+16);const files=[];
|
|
for(let n=0;n<count;n++){
|
|
if(buffer.readUInt32LE(offset)!==0x02014b50)throw new Error('ZIP 中央目录损坏');
|
|
const method=buffer.readUInt16LE(offset+10),compressed=buffer.readUInt32LE(offset+20),nameLength=buffer.readUInt16LE(offset+28),extraLength=buffer.readUInt16LE(offset+30),commentLength=buffer.readUInt16LE(offset+32),local=buffer.readUInt32LE(offset+42);
|
|
const name=buffer.subarray(offset+46,offset+46+nameLength).toString('utf8');
|
|
const localName=buffer.readUInt16LE(local+26),localExtra=buffer.readUInt16LE(local+28),start=local+30+localName+localExtra;
|
|
const raw=buffer.subarray(start,start+compressed);
|
|
const data=method===0?Buffer.from(raw):method===8?zlib.inflateRawSync(raw):(()=>{throw new Error('不支持的压缩方式 '+method);})();
|
|
files.push({name,data});offset+=46+nameLength+extraLength+commentLength;
|
|
}
|
|
return files;
|
|
}
|
|
module.exports={unzip};
|