在 Node.js 中压缩包含换行符的文本文件会导致损坏的 gzip 文件

Compressing text file containing new line characters in Node.js results in corrupt gzip file

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

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

End-of-central-directory signature not found. Either this file is not a zipfile, or it constitutes one disk of a multi-part archive. In the latter case the central directory and zipfile comment will be found on the last disk(s) of this archive.

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

我使用 Mac OS 10.15.3 和节点 12.14.1。

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;
  }
});

Gzip 不是 ZIP。 Gzip 仅压缩单个流; ZIP 是一种将多个文件打包成一个存档的存档格式,每个文件都可以用不同的方法压缩,也可以不压缩。

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