Skip to content
On this page

adm-zip

简介

adm-zip 是一个用于处理 ZIP 文件的 Node.js 库,提供了创建、解压、修改和提取 ZIP 文件的功能。

安装

bash
npm install adm-zip

基本使用

1. 创建 ZIP 文件

javascript
const AdmZip = require('adm-zip')

// 创建新的 ZIP 文件
const zip = new AdmZip()

// 添加文件
zip.addFile('test.txt', Buffer.from('Hello World'))

// 添加本地文件
zip.addLocalFile('/path/to/file.txt')

// 写入 ZIP 文件
zip.writeZip('output.zip')

2. 解压 ZIP 文件

javascript
const zip = new AdmZip('example.zip')

// 解压到指定目录
zip.extractAllTo('/path/to/extract', true) // true 表示覆盖已存在的文件

高级特性

1. 读取 ZIP 内容

javascript
const zip = new AdmZip('example.zip')

// 获取所有条目
const entries = zip.getEntries()

entries.forEach((entry) => {
  console.log(entry.entryName)

  // 读取文件内容
  const content = entry.getData().toString('utf8')
  console.log(content)
})

2. 添加目录

javascript
const zip = new AdmZip()

// 添加整个目录
zip.addLocalFolder('/path/to/folder')

// 添加带有过滤的目录
zip.addLocalFolder('/path/to/folder', 'prefix/', (filename) => {
  return !filename.endsWith('.tmp')
})

3. 修改 ZIP 文件

javascript
const zip = new AdmZip('existing.zip')

// 删除文件
zip.deleteFile('unnecessary.txt')

// 更新文件
zip.updateFile('existing.txt', Buffer.from('New content'))

// 保存修改
zip.writeZip()

最佳实践

  1. 错误处理

    javascript
    try {
      const zip = new AdmZip('example.zip')
      zip.extractAllTo('output/')
    } catch (err) {
      console.error('ZIP 处理失败:', err)
    }
  2. 大文件处理

    javascript
    const zip = new AdmZip()
    zip.addLocalFile('large-file.dat', {
      compress: true,
      level: 9, // 最高压缩级别
    })
  3. 内存管理

    javascript
    // 流式处理大文件
    const fs = require('fs')
    const zip = new AdmZip()
    
    const stream = fs.createReadStream('large-file.dat')
    zip.addFile('large-file.dat', stream)

注意事项

  1. 处理大文件时注意内存使用
  2. 解压前验证 ZIP 文件完整性
  3. 注意文件路径的跨平台兼容性
  4. 处理中文文件名时需要注意编码
  5. 建议使用异步操作处理大文件

要保持清醒 永远不抱有意外的幻想 凭空的期待最要命