You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Node.js zlib模块解压文件时遭遇EISDIR 4068错误的解决方法

解决Node.js zlib解压ZIP出现EISDIR 4068错误的问题

错误原因

  1. EISDIR错误直接诱因:代码中fs.createWriteStream的目标是目录unzipDirectory,但流仅能写入文件,无法直接向目录写入数据,因此触发该错误。
  2. 核心本质问题:Node.js内置的zlib模块不支持ZIP格式解压,它仅能处理gzip、deflate这类单文件压缩格式。ZIP属于多文件归档格式,包含完整的文件目录结构,zlib没有解析这类复杂结构的能力。

解决方案

情况1:文件实际是gzip压缩(后缀名误写为.zip)

如果test.zip只是单个文件的gzip压缩包(只是后缀名误用了zip),修改代码将输出指向具体文件,并确保输出目录存在:

const fs = require('fs');
const zlib = require('zlib');
const path = require('path');

const zipFilePath = path.join(__dirname, 'test.zip');
// 指定输出的具体文件名,替换成你实际需要的文件名
const outputFilePath = path.join(__dirname, 'unzipdir', 'extracted-file.txt');

// 递归创建输出目录(如果不存在)
fs.mkdirSync(path.dirname(outputFilePath), { recursive: true });

const readStream = fs.createReadStream(zipFilePath);
const writeStream = fs.createWriteStream(outputFilePath);

readStream.pipe(zlib.createGunzip()).pipe(writeStream);

writeStream.on('finish', () => {
  console.log('解压完成');
});

readStream.on('error', (err) => {
  console.error('读取压缩文件错误:', err);
});

writeStream.on('error', (err) => {
  console.error('写入解压文件错误:', err);
});

情况2:确实需要解压ZIP归档文件

由于Node.js内置模块没有提供ZIP解析能力,需使用第三方库,比如adm-zip或extract-zip:

  1. 安装依赖:
npm install adm-zip
  1. 使用示例:
const AdmZip = require('adm-zip');
const path = require('path');

const zipFilePath = path.join(__dirname, 'test.zip');
const unzipDirectory = path.join(__dirname, 'unzipdir');

const zip = new AdmZip(zipFilePath);
zip.extractAllTo(unzipDirectory, true); // true表示覆盖已存在的文件

console.log('ZIP文件解压完成');

如果必须仅用内置模块实现ZIP解压,需要手动解析ZIP文件的文件头、中央目录等二进制结构,这涉及复杂的字节流处理,不推荐用于生产环境。

内容的提问来源于stack exchange,提问作者stckvrw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 09:43:15