How to read an archive in a Tabris.js app
Have you ever had to deal with a ZIP file in your mobile app? Since Tabris.js app developers have the npm ecosystem at hand, unzipping ZIP files in a cross-platform way is just a npm install
away.
In this post, we are going to use the npm module jszip
to print the contents of a zip file.
The zip file that we are going to read is available here. It has the following structure and contents:
.
├── a folder
│ └── message.txt (Hello world!)
└── another-message.txt (Hello earth!)
First, let’s download the archive:
1 2 |
const response = await fetch('https://tabris.com/wp-content/uploads/2020/07/zipfile.zip') const archive = await response.arrayBuffer(); |
Let’s see what it contains. loadAsync()
reads the ZIP and provides information about the contained files. Its result has a forEach()
method that can be used to iterate over the zip entries.
1 2 3 4 5 6 7 8 9 10 |
const JSZip = require('jszip'); const result = await JSZip.loadAsync(archive); result.forEach((path, entry) => console.log(entry.name)); /** * a folder/ * a folder/message.txt * another-message.txt */ |
In this blog post, we want to print the content of every file in the zip, so the folder entry is not interesting for us. Let’s filter it out.
1 2 3 4 5 6 7 |
result.filter((path, entry) => !entry.dir) .forEach(file => console.log(file.name)); /** * a folder/message.txt * another-message.txt */ |
That’s better! Let’s read the file contents as text and print them to the console:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
result.filter((path, entry) => !entry.dir) .forEach(async file => { const contents = await file.async('text'); console.log('Path:\n', file.name, '\nContents:\n', contents, '\n') }); /** * Path: * a folder/message.txt * Contents: * Hello world! * * Path: * another-message.txt * Contents: * Hello earth! */ |
That’s it!
Here is the full example code:
1 2 3 4 5 6 7 8 9 10 11 12 |
const JSZip = require('jszip'); (async () => { const response = await fetch('https://tabris.com/wp-content/uploads/2020/07/zipfile.zip') const archive = await response.arrayBuffer(); const result = await JSZip.loadAsync(archive); result.filter((path, entry) => !entry.dir) .forEach(async file => { const contents = await file.async('text'); console.log('Path:\n', file.name, '\nContents:\n', contents, '\n') }); })().catch(error => console.error(error)); |
Fiddle with this example and run it in the Tabris.js delevoper app (Android/iOS) now:
Stay tuned for a follow-up on how to unpack the contents of the ZIP file to the device file storage in a worker!
Feedback is welcome!
Want to join the discussion?Feel free to contribute!