Skip to content

Instantly share code, notes, and snippets.

@khaledosman
Last active April 17, 2023 05:26
Show Gist options
  • Save khaledosman/205e079bfbc1df34f08d6fedc330445b to your computer and use it in GitHub Desktop.
Save khaledosman/205e079bfbc1df34f08d6fedc330445b to your computer and use it in GitHub Desktop.
recursively add specific files within a directory to a zipfile using NodeJS & JsZip
const fs = require('fs')
const path = require('path')
const JSZip = require('jszip')
const { promisify } = require('util')
const readFile = promisify(fs.readFile)
const readDir = promisify(fs.readdir)
const lstat = promisify(fs.lstat)
function addFilesToZip (jsZip, directoryPath, filesToInclude) {
const promiseArr = filesToInclude.map(async file => {
const filePath = path.join(directoryPath, file)
try {
const fileStats = await lstat(filePath)
const isDirectory = fileStats.isDirectory()
if (isDirectory) {
const directory = jsZip.folder(file)
const subFiles = await readDir(filePath)
return addFilesToZip(directory, filePath, subFiles)
} else {
const fileContent = await readFile(filePath)
return jsZip.file(file, fileContent)
}
} catch (err) {
// console.log(err)
return Promise.resolve()
}
})
return Promise.all(promiseArr)
}
async function createZipFromFiles (directoryPaths, filesToInclude, dontCreateTopLevelFolder = false) {
const jsZip = new JSZip()
await Promise.all(
directoryPaths.map(directoryPath => {
const parsed = path.parse(directoryPath)
const folder = dontCreateTopLevelFolder ? jsZip : jsZip.folder(parsed.base)
return addFilesToZip(folder, directoryPath, filesToInclude)
})
)
return jsZip
}
module.exports.generateZipFromFiles = function generateZipFromFiles (directoryPaths, filesToInclude, outputPath) {
return new Promise(async (resolve, reject) => {
const jsZip = await createZipFromFiles(directoryPaths, filesToInclude, true)
jsZip.generateNodeStream({ type: 'nodebuffer', streamFiles: true })
.pipe(fs.createWriteStream(outputPath))
.on('finish', () => {
console.log(`${outputPath} written.`)
resolve(outputPath)
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment