您的观察很准确!如果发现压缩后的 ZIP 文件中仍然保留目录结构,可能是以下原因导致的:
### 主要原因和解决方案
1. **`archive.file()` 的 `name` 参数未生效**
```javascript
// 错误写法(可能意外保留了路径)
archive.file(processedPath, { name: processedPath }); // ❌ 仍然传了完整路径
// 正确写法(应只传文件名)
archive.file(processedPath, {
name: path.basename(processedPath) // ✅ 仅保留文件名
});
```
2. **路径标准化问题(Windows反斜杠)**
```javascript
// 处理Windows路径分隔符问题
const flatName = path.basename(processedPath).replace(/\\/g, '/');
archive.file(processedPath, { name: flatName });
```
3. **文件实际写入时机问题**
```javascript
// 确保在调用 finalize() 前所有文件已添加
archive.file(processedPath, { name: path.basename(processedPath) });
archive.finalize(); // 必须在所有文件添加后调用
```
### 完整修正代码
```javascript
const zipFileName = path.basename(fullPath, path.extname(fullPath)) + '.zip';
const zipPath = path.join(downloadDir, zipFileName);
const output = fs.createWriteStream(zipPath);
const archive = archiver('zip', { zlib: { level: 9 } });
await new Promise((resolve, reject) => {
output.on('close', resolve);
archive.on('error', reject);
archive.pipe(output);
// 关键修正点:强制扁平化路径
const entryName = path.basename(processedPath);
console.log('ZIP内文件名:', entryName); // 调试确认
archive.file(processedPath, {
name: entryName // 确保只使用纯文件名
});
archive.finalize();
});
console.log('压缩完成,请检查ZIP内容');
```
### 验证步骤
1. **检查控制台输出**:
- 确认 `entryName` 日志输出确实是纯文件名(如 `file.htm` 而非 `path/to/file.htm`)
2. **手动检查ZIP内容**:
```bash
# 使用命令行工具检查
unzip -l yourfile.zip
```
应该看到类似:
```
Archive: yourfile.zip
Length Date Time Name
--------- ---------- ----- ----
123 2023-01-01 12:34 example_processed.htm
```
3. **路径处理备选方案**:
```javascript
// 更彻底的路径扁平化方法
function flattenPath(p) {
return p.split(path.sep).pop(); // 确保取最后一段
}
archive.file(processedPath, { name: flattenPath(processedPath) });
```
如果问题仍然存在,可能是:
1. 使用的 `archiver` 版本有bug(尝试升级到最新版)
2. 文件在添加后被意外修改(检查是否有其他代码干扰)
3. 查看的ZIP文件不是新生成的文件(确认路径是否正确)