JSZip

Introduction

JSZip is a utility library that allows you to create, edit, and generate compressed files. This library is adapted based on JSZip v3.5.0 to ensure compatibility with OpenHarmony, while retaining its original usage and features.

How to Install

ohpm install @ohos/jszip

For details about the OpenHarmony ohpm environment configuration, see OpenHarmony HAR.

Available APIs

API Parameter Description
file (path,data[, options]) Creates a file.
folder (name) Creates a folder.
forEach (callback:(relativePath,file) => void) Traverses directories and files.
filter (predicate:(relativePath,file) => boolean) Filters a directory or file.
remove (path) Removes a directory or file.
generateAsync (options,onUpdate) Asynchronously generates a compressed file. It supports password setting.
loadAsync (data,options) Asynchronously loads a compressed file.

Example

Create a JSZip instance.

import JSZip from "@ohos/jszip";

const jszip = new JSZip();

Create a file.

jszip.file("xxx.txt,""This is a piece of text");

Create a folder.

jszip.folder("xxx");

Create a file or folder in a specified directory.

const folder = jszip.folder("xxx");

folder.folder("xxx");
folder.file("xxx.txt,""This is a piece of text.");

Asynchronously generate a compressed file.

jszip.generateAsync({ type: "arraybuffer"})

Asynchronously generate an encrypted compressed file.

jszip.generateAsync({ type: "arraybuffer", password: "1234", encryptStrength: 3 })

Asynchronously load a compressed file.

jszip.loadAsync(data)

Decompress an encrypted compressed file.

  1. Decompress an encrypted compressed file generated by the demo.

  2. Import an encrypted file to the cache or files folder in the application sandbox path and decompress the file. (Note that the imported file must be readable and writable. Otherwise, an error message is displayed.)

The sample code for decompressing a file in the preceding two scenarios is as follows:

 // Verify the parameter.
 if (!this.filePath || this.filePath.length < 1) {
  promptAction.showToast({
    message: 'No file is available. Encrypt the compressed file first.'
  })
  return;
}
if (!this.password || this.password.length < 1) {
  promptAction.showToast({
    message: 'Enter the password for decompression first.'
  })
  return;
}
try {

   // Check whether the user has the permission to process the file.
  let isAccess: boolean = fs.accessSync(this.filePath)
  if (!isAccess) {
    promptAction.showToast({
      message: 'You do not have the permission to process the ${this.filePath} file.'
    })
    return
  }
   // Read the local file in the application sandbox path and convert it into the Uint8Array format. A too large file may cause an out of memory (OOM) error.
  let totalSize = fs.statSync(this.filePath).size;
  let fileId = fs.openSync(this.filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
  let cacheData: Uint8Array = new Uint8Array(totalSize);
  let readLength = 0;
  let buff = new ArrayBuffer(8 * 1024)
  let readSize = 0;
  while (readLength < totalSize) {
    if (readLength + buff.byteLength < totalSize) {
      readSize = fs.readSync(fileId.fd, buff, {
        offset: readLength,
        length: buff.byteLength
      })
      cacheData.set(new Uint8Array(buff), readLength)
    } else {
      let trueLength = totalSize - readLength
      readSize = fs.readSync(fileId.fd, buff, {
        offset: readLength,
        length: trueLength
      })
      let trueBuff = buff.slice(0, trueLength)
      cacheData.set(new Uint8Array(trueBuff), readLength)
    }
    readLength += readSize;
  }
  // Add a password to decompress the file.
  JSZip.loadAsync(cacheData, {
    password: this.password
  }).then((data: JSZip) => {
    promptAction.showToast({
      message: 'The encrypted file is decompressed successfully. ${JSON.stringify(data) }'
    })
  }).catch((err: Error) => {
    promptAction.showToast({
      message: 'Failed to decompress the encrypted file. Error cause: ${err.message}'
    })
  })
} catch (err) {
  promptAction.showToast({
    message: 'An error occurred when decompressing the encrypted file. Error cause: ${err.message}'
  })
}

  1. Decompress an encrypted compressed file in the rawfile folder of the project.

      try {
       // Pass in the file name in rawfile and encrypt the compressed file, for example, using an encryption software on the PC.
      loadAsyncFromRawFile(this.rawFileName).then((res: Uint8Array | void) => {
        if (!res) {
          promptAction.showToast({
            message: 'The compressed file is not found.'
          })
          this.closeLoading()
          return
        }
          // After reading the file data, transfer the data to JSZip for decompression.
        this.instance.loadAsync(res, {
          password: this.password
        }).then((data: JSZip) => {
          promptAction.showToast({
            message: 'The encrypted file is decompressed successfully. ¥${JSON.stringify (data) }'
          })
        }).catch((err: Error) => {
          promptAction.showToast({
            message: 'Failed to decompress the encrypted file. Error cause: ${err.message}'
          })
        })
      })
    } catch (err) {
      promptAction.showToast({
        message: 'An error occurred when decompressing the encrypted file. Error cause: ${err.message}'
      })
    }
    

About obfuscation

  • Code obfuscation, please seeCode Obfuscation
  • If you want the jszip library not to be obfuscated during code obfuscation, you need to add corresponding exclusion rules in the obfuscation rule configuration file obfuscation-rules.txt:
-keep
./oh_modules/@ohos/jszip

Constraints

This project has been verified in the following versions:

  • DevEco Studio: NEXT Beta1-5.0.3.806, SDK: API 12 Release (5.0.0.66)
  • DevEco Studio: 4.1.3.313, SDK: API 11 (4.1.2.1)

Directory Structure

|---- jszip
|     |---- AppScrope  # Sample code
|     |---- entry  # Sample code
|     |---- jszip  # JSZip library folder
|           |---- src  # Module code
|                |---- core   # JSZip core code
|                |---- dist   # Code generated by the packaging script
|                |---- type   # Type declaration file
|            |---- index.ets          # Entry file
|            |---- *.json5      # Configuration file
|           |---- rollup.config.js      # Rollup configuration file
|     |---- README.md  # Readme
|     |---- README_zh.md  # Readme        
|     |---- README.OpenSource  # Open source description
|     |---- CHANGELOG.md  # Changelog

License

This project is licensed under Apache License 2.0.

How to Contribute

If you find any problem when using the project, submit an issue or a PR.