Last active
April 17, 2023 05:26
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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