Skip to content

Instantly share code, notes, and snippets.

@loilo
Created August 18, 2022 16:25
Show Gist options
  • Save loilo/eecdf1e9507257fffea2dc15c77a0680 to your computer and use it in GitHub Desktop.
Save loilo/eecdf1e9507257fffea2dc15c77a0680 to your computer and use it in GitHub Desktop.
Simple .zip file generation with JavaScript using JSZip

Simple .zip file generation with JavaScript using JSZip

The zipTree function exported from this module takes a file tree object and creates a zip object from it using JSZip (which you need to install first via npm install jszip):

// A tree is just a collection of file names mapped to their contents
let data = {
  // Use a string for text content
  'file.txt': '...file content...',

  // Use a plain object for folders
  'my-folder': {
    'another-file.txt': '...file content...'
  },

  // Use other kinds of objects (e.g. Blob) to add binary data
  'image': someBlob,
  
  // Use an array to pass content and JSZip options
  'with-options.txt': ['...file content...', { date: new Date(2012, 11, 21) }]
}

// Create the JSZip object
let zipObject = zipTree(data)

// Now save the zip object as you like, e.g. using FileSaver.js
import JSZip from 'jszip'
export function zipTree(tree) {
let zip = new JSZip()
function walkTree(target, tree) {
for (let [name, content] of Object.entries(tree)) {
let options
if (Array.isArray(content)) {
options = content[1]
content = content[0]
}
if (typeof content === 'object' && content.toString() === '[object Object]') {
let folder = target.folder(name, content, options)
walkTree(folder, content)
} else {
target.file(name, content, options)
}
}
}
walkTree(zip, tree)
return zip
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment