node.js - 在 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;
}
});
解决方案
Gzip 不是 ZIP。Gzip 只压缩单个流;ZIP 是一种将多个文件打包到一个存档中的存档格式,每个文件也可以用不同的方法压缩或根本不压缩。
要解压缩您使用 Gzip 压缩的内容,请使用该gunzip
工具。
推荐阅读
- .htaccess - .htaccess 文件中的子域仅适用于索引
- python - 如何获取函数的打印输出并将其放入 DataFrame
- python - 如何在文件夹中找到特定类型的所有对象?
- php - 如何在php中只获得一级目录名称
- stripe-payments - 如何通过 Stripe redirectToCheckout 函数传递元数据
- suitescript - 如何从带有某些字段来源的按钮导航到自定义记录?(suitescript 2.0)
- c++ - 为什么 QDialogButtonBox 标签的语言在设计和执行之间会发生变化?
- python - 有没有办法使用消息 ID 编辑特定消息。不和谐
- php - 通过 CSV 将自定义分类法导入 WooCommerce
- python - 以 10 为底的 int() 的 Django 无效文字:b'11 20:11:22'