我有一个用 ZLIB 压缩的 22 字节有效负载。我可以使用以下代码片段在 Java 中将文件解压缩为原始 14 字节字符串:
public static void main(String[] args) throws Exception {
byte[] compressedData = readFile(INPUT_FILE);
System.out.println("Compressed data (hex): " + bytesToHex(compressedData));
System.out.println("Compressed data length: " + compressedData.length);
byte[] uncompressedData = inflateData(compressedData, UNCOMPRESSED_LENGTH);
String outputString = new String(uncompressedData);
System.out.println("Uncompressed data: " + outputString);
}
public static byte[] readFile(String filePath) throws IOException {
try (FileInputStream fis = new FileInputStream(filePath); FileChannel fileChannel = fis.getChannel()) {
ByteBuffer buffer = ByteBuffer.allocate((int) fileChannel.size());
fileChannel.read(buffer);
return buffer.array();
}
}
public static byte[] inflateData(byte[] compressedData, int uncompressedLength) throws DataFormatException, IOException {
Inflater inflater = new Inflater();
inflater.setInput(compressedData);
byte[] uncompressedData = new byte[uncompressedLength];
int resultLength = inflater.inflate(uncompressedData);
if (resultLength != uncompressedLength) {
throw new IOException("Unexpected uncompressed length: expected " + uncompressedLength + ", got " + resultLength);
}
inflater.end();
return uncompressedData;
}
但是在 NodeJS 中我无法膨胀这个文件。我尝试过使用这些选项,也尝试过 Pako,但没有成功。
const compressed = fs.readFileSync(INPUT_FILE);
console.log(`Compressed data (hex): ${compressed.toString('hex')}`);
console.log(`Compressed data length: ${compressed.length}`);
const uncompressedData: Buffer = await inflateAsync(compressed);
console.log(`Decompressed data length: ${uncompressedData.length}`);
if (uncompressedData.length !== UNCOMPRESSED_LENGTH) {
throw new Error(`Unexpected uncompressed length: expected ${UNCOMPRESSED_LENGTH}, got ${uncompressedData.length}`);
}
当前错误是
Error: unexpected end of file
。我对此有点困惑,你知道发生了什么事吗?
仅供参考:这个 22 字节文件的十六进制字符串是
789cf2cacfc8cbab5408c928cd4b492d02000000ffff
,并且在 Java 和 NodeJS 代码中输出相同。
您的数据是不完整的 zlib 流。报告的错误是正确的。