首页 > 解决方案 > 在 Node.js 中压缩包含换行符的文本文件会导致 gzip 文件损坏

问题描述

按照下面直接从https://nodejs.org/api/zlib.html#zlib_zlib复制的简单代码示例,如果输入文本文件包含换行符,将导致 gzip 文件损坏!

使用从终端解压缩生成的文件时unzip input.txt.gz出现以下错误(通过在 Finder 中双击文件进行解压缩将产生类似的错误):

未找到中央目录结束签名。此文件不是 zip 文件,或者它构成多部分存档的一个磁盘。在后一种情况下,中央目录和 zipfile 注释将在此存档的最后一个磁盘上找到。

我错过了什么?Surly 您必须能够压缩包含换行符的文本文件?!

我使用带有节点 12.14.1 的 Mac OS 10.15.3。

input.txt(尝试插入尾随换行符,但没有区别):

hello
world

Node.js 代码:

const { createGzip } = require('zlib');
const { pipeline } = require('stream');
const {
  createReadStream,
  createWriteStream
} = require('fs');

const gzip = createGzip();
const source = createReadStream('input.txt');
const destination = createWriteStream('input.txt.gz');

pipeline(source, gzip, destination, (err) => {
  if (err) {
    console.error('An error occurred:', err);
    process.exitCode = 1;
  }
});

标签: node.jsgzipnewline

解决方案


Gzip 不是 ZIP。Gzip 只压缩单个流;ZIP 是一种将多个文件打包到一个存档中的存档格式,每个文件也可以用不同的方法压缩或根本不压缩。

要解压缩您使用 Gzip 压缩的内容,请使用该gunzip工具。


推荐阅读