ZIP archives

suggest change

While Node.js includes the built-in node:zlib module for raw Gzip and Deflate compression, creating and extracting standard multi-file .zip containers typically relies on popular, battle-tested ecosystem libraries:


1. Creating a ZIP Archive with archiver

archiver is stream-based, meaning it can compress files directly to disk or over an HTTP connection without loading the entire archive into memory.

Installation

npm install archiver

Zipping Files and Directories

import fs from 'node:fs';
import path from 'node:path';
import { ZipArchive } from 'archiver';

async function createZipArchive(sourceDir, outputPath) {
  return new Promise((resolve, reject) => {
    // 1. Create a write stream for the output file
    const output = fs.createWriteStream(outputPath);
    const archive = new ZipArchive({
      zlib: { level: 9 } // Maximum compression level (0-9)
    });

    // 2. Listen for completion and warning events
    output.on('close', () => {
      console.log(`Archive finalized. Total bytes: ${archive.pointer()}`);
      resolve();
    });

    archive.on('warning', (err) => {
      if (err.code === 'ENOENT') {
        console.warn('File not found warning:', err);
      } else {
        reject(err);
      }
    });

    archive.on('error', (err) => reject(err));

    // 3. Pipe archive data to the output file stream
    archive.pipe(output);

    // 4. Append individual files or strings
    archive.append('Hello, World!', { name: 'hello.txt' });
    archive.file(path.join(sourceDir, 'config.json'), { name: 'settings/config.json' });

    // 5. Append an entire directory tree
    archive.directory(sourceDir, 'files');

    // 6. Finalize the archive (flush remaining streams)
    archive.finalize();
  });
}

createZipArchive('./my-docs', './output.zip')
  .then(() => console.log('Successfully created output.zip'))
  .catch(console.error);

Streaming a ZIP Directly as an HTTP Response (Express)

import express from 'express';
import { ZipArchive } from 'archiver';

const app = express();

app.get('/download-report', (req, res) => {
  res.attachment('report.zip'); // Sets Content-Disposition and MIME type

  const archive = new ZipArchive({ zlib: { level: 6 } });

  archive.on('error', (err) => {
    res.status(500).send({ error: err.message });
  });

  // Pipe the compressed stream directly to the HTTP response
  archive.pipe(res);

  archive.append('Monthly Report Content...', { name: 'report.txt' });
  archive.file('./assets/logo.png', { name: 'logo.png' });

  archive.finalize();
});

2. In-Memory ZIP Creation with adm-zip

For smaller archives or quick scripts, adm-zip allows straightforward synchronous in-memory operations:

Installation

npm install adm-zip

Creating and Saving

import AdmZip from 'adm-zip';

const zip = new AdmZip();

// Add local files
zip.addLocalFile('./package.json');

// Add text or buffer directly
zip.addFile('notes.txt', Buffer.from('Meeting notes from Monday'));

// Add an entire folder
zip.addLocalFolder('./dist', 'dist');

// Write out to disk
zip.writeZip('./bundle.zip');
console.log('ZIP created successfully!');

3. Extracting ZIP Archives

Extracting with adm-zip

import AdmZip from 'adm-zip';

const zip = new AdmZip('./bundle.zip');

// Extract everything into a target folder
zip.extractAllTo('./extracted', /* overwrite */ true);

// Or iterate over entries to inspect before extracting
const zipEntries = zip.getEntries();
for (const entry of zipEntries) {
  console.log(`Entry: ${entry.entryName}, Compressed Size: ${entry.header.compressedSize}`);
  if (entry.entryName === 'notes.txt') {
    const content = entry.getData().toString('utf8');
    console.log('notes.txt content:\n', content);
  }
}

Streaming Extraction with unzipper

For large archives, unzipper decompresses on the fly to avoid buffering entire archives into RAM:

npm install unzipper
import fs from 'node:fs';
import unzipper from 'unzipper';

fs.createReadStream('./bundle.zip')
  .pipe(unzipper.Extract({ path: './extracted-stream' }))
  .on('close', () => {
    console.log('Extraction complete!');
  });

4. Security: Preventing the "Zip Slip" Vulnerability

When extracting archives supplied by untrusted users, always prevent directory traversal attacks (where a malicious archive contains filenames like ../../etc/passwd or ..\Windows\System32\cmd.exe).

import path from 'node:path';
import unzipper from 'unzipper';
import fs from 'node:fs';

async function safeExtract(zipPath, destinationDir) {
  const resolvedTarget = path.resolve(destinationDir);

  const directory = await unzipper.Open.file(zipPath);

  for (const file of directory.files) {
    const targetPath = path.resolve(resolvedTarget, file.path);

    // Guard: Prevent extraction outside destination directory
    if (!targetPath.startsWith(resolvedTarget + path.sep) && targetPath !== resolvedTarget) {
      throw new Error(`Security Exception: Zip Slip path traversal attempt: ${file.path}`);
    }

    if (file.type === 'Directory') {
      await fs.promises.mkdir(targetPath, { recursive: true });
    } else {
      await fs.promises.mkdir(path.dirname(targetPath), { recursive: true });
      await new Promise((resolve, reject) => {
        file.stream()
          .pipe(fs.createWriteStream(targetPath))
          .on('finish', resolve)
          .on('error', reject);
      });
    }
  }
}

5. Summary and Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents