jszip icon indicating copy to clipboard operation
jszip copied to clipboard

Decompressing Folder to files (text)

Open RUSHt opened this issue 9 years ago • 7 comments

I needed to Un-Zip a folder in node js.

I could easily get to the list of fileNames, but could only do the following to extract the file content.

String.fromCharCode.apply(null, zip.files[fileName]._data.compressedContent)

I am sure this is not the right approach, but could find nothing in the documentation to advise me to the correct method.

RUSHt avatar Oct 08 '17 10:10 RUSHt

I'm trying to find an example for extracting all contents of a zip to a folder too. All examples stop after

zip.loadAsync(data)
.then(content => {
  // list all the files
  console.log(Object.keys(content.files));
  // what next?
})

pennyfx avatar Nov 09 '17 20:11 pennyfx

Use https://github.com/maxogden/extract-zip

pennyfx avatar Nov 09 '17 22:11 pennyfx

Just for future use, after that you can read the content of each file by the help of async: http://stuk.github.io/jszip/documentation/api_zipobject/async.html like this:

  // Closure to capture the file information.
  function handleFile(f) {
    JSZip.loadAsync(f)                                  
      .then(function(zip) {
          zip.forEach(function (relativePath, zipEntry) {  
              zipEntry.async("blob") .then(function (content) { fileReader.readAsArrayBuffer(content); });
          });
      }, function (e) {
          alert("Error reading " + f.name + ": " + e.message);
      });
  }

pesarkhobeee avatar Jan 04 '18 11:01 pesarkhobeee

@pesarkhobeee The URL seems to be broken, changing it to a https URL seems to work: http://stuk.github.io/jszip/documentation/api_zipobject/async.html

stefnotch avatar Aug 27 '18 09:08 stefnotch

How can we extract files from .zip using jszip? I want to open those files in different application...

vparte7 avatar Jul 18 '19 14:07 vparte7

JSZip.loadAsync(this.$dataFileUpload) .then(function(zip) { zip.forEach(function (relativePath, zipEntry) { zipEntry.async("blob") .then(function (content) { if (content.size>0){ const url = window.URL.createObjectURL(content); const link = document.createElement('a'); if (link.download !== undefined) { // feature detection link.setAttribute('href', url); link.setAttribute('download', relativePath); link.style.visibility = 'hidden'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } } }); }); }, function (e) { alert("Error reading " + data.name + ": " + e.message); });

luisomargranados avatar Sep 02 '23 01:09 luisomargranados

I laughed a bit at the pennyfx's comment. That is what I feel as well. The examples seem to just stop there. It took me a while to figure out the complete code, so I thought I should share it here:

async extractZipFileToPath (file: string, outputPath: string): Promise<void> {
    if (!fs.existsSync(outputPath)) {
      fs.mkdirSync(outputPath, { recursive: true })
    }

    const data = fs.readFileSync(file)

    const zip = await JSZip.loadAsync(data, { createFolders: true })

    await new Promise<void>((resolve, reject) => {
      let entryCount = 0
      let errorOut = false

      zip.forEach(() => { entryCount++ }) // there is no other way to count the number of entries within the zip file.

      zip.forEach((relativePath, zipEntry) => {
        if (errorOut) {
          return
        }

        const outputEntryPath = path.join(outputPath, relativePath)
        if (zipEntry.dir) {
          if (!fs.existsSync(outputEntryPath)) {
            fs.mkdirSync(outputEntryPath, { recursive: true })
          }

          entryCount--

          if (entryCount === 0) {
            resolve()
          }
        } else {
          void zipEntry.async('blob')
            .then(async (content) => Buffer.from(await content.arrayBuffer()))
            .then((buffer) => {
              const stream = fs.createWriteStream(outputEntryPath)
              stream.write(
                buffer,
                (error) => {
                  if (error) {
                    reject(error)
                    errorOut = true
                  }
                }
              )
              stream.on('finish', () => {
                entryCount--

                if (entryCount === 0) {
                  resolve()
                }
              })
              stream.end() // extremely important on Windows. On Mac / Linux, not so much since those platforms allow multiple apps to read from the same file. Windows doesn't allow that.
            })
            .catch((e) => {
              errorOut = true
              reject(e)
            })
        }
      })
    })
  }

This works on Windows, Mac, and Linux. The code is used in production (https://superintendent.app). We don't have nested directories though, but I still hope this is helpful.

tanin47 avatar May 06 '24 22:05 tanin47