使用archivejs库归档含多文件文件夹,如何让文件处于Zip包根目录?
我懂你这个痛点!之前用archiver.js(应该是你说的archivejs?Node.js里常用的压缩库是archiver)打包文件夹时,默认会把原文件夹的层级也塞进zip里,结果打开压缩包还得先点进原文件夹才能看到文件,特别烦。刚好我之前解决过一模一样的问题,给你两种场景的解决方案:
场景1:只打包目标文件夹下的直接文件到压缩包根目录
如果你的download文件夹里只有直接文件(没有子文件夹),或者你只需要这些直接文件,那用archiver.directory()方法就能轻松搞定——第二个参数传false,就不会把download这个父文件夹加到zip里,而是直接把里面的文件放到根目录:
const fs = require('fs'); const archiver = require('archiver'); const path = require('path'); // 替换成你的目标文件夹绝对路径 const sourceDir = '/absolute/path/to/download'; // 输出的zip文件路径(可以自定义) const outputPath = path.join(__dirname, 'download.zip'); const output = fs.createWriteStream(outputPath); const archive = archiver('zip', { zlib: { level: 9 } }); // zlib级别越高压缩率越高 // 监听打包完成事件 output.on('close', () => { console.log(`打包搞定!总大小:${archive.pointer()} bytes`); }); // 处理打包错误 archive.on('error', (err) => { throw err; }); // 核心操作:把sourceDir里的内容直接放到zip根目录,不创建父文件夹 archive.directory(sourceDir, false); // 启动打包流程 archive.pipe(output); archive.finalize();
场景2:打包所有文件(含子文件夹内的)并扁平化到根目录
如果你的download文件夹里有子文件夹,并且希望子文件夹里的文件也直接放到zip根目录(完全抛弃原层级结构),那得递归遍历所有文件,逐个添加时指定文件名(去掉原路径前缀):
const fs = require('fs'); const archiver = require('archiver'); const path = require('path'); const sourceDir = '/absolute/path/to/download'; const outputPath = path.join(__dirname, 'download.zip'); const output = fs.createWriteStream(outputPath); const archive = archiver('zip', { zlib: { level: 9 } }); output.on('close', () => { console.log(`全部打包完成,总大小:${archive.pointer()} bytes`); }); archive.on('error', (err) => { throw err; }); // 递归遍历文件夹,把所有文件扁平化添加到zip根目录 function flattenAddFiles(dir) { const items = fs.readdirSync(dir); items.forEach(item => { const fullPath = path.join(dir, item); const stats = fs.statSync(fullPath); if (stats.isFile()) { // 只保留文件名,忽略原路径 const fileName = path.basename(fullPath); archive.file(fullPath, { name: fileName }); console.log(`已添加:${fileName}`); } else if (stats.isDirectory()) { // 递归处理子文件夹 flattenAddFiles(fullPath); } }); } // 开始添加所有文件 flattenAddFiles(sourceDir); // 完成打包 archive.pipe(output); archive.finalize();
重要提醒
- 如果有重名文件,后面添加的会直接覆盖前面的!所以要么确保所有文件名唯一,要么在代码里加个重名处理逻辑(比如给文件名加个序号前缀)。
- 先确认你已经安装了archiver:运行
npm install archiver就行。
内容的提问来源于stack exchange,提问作者Morten
相关产品推荐
相关产品推荐

