How to read an archive on a background thread in a Tabris.js app
This is a follow-up on the previous blog post about “How to read an archive in a Tabris.js app“.
Today, we are going to use a Worker available in Tabris.js to read the content of an archive file. The Worker allows users to do heavy operations on a background thread without blocking the main (UI) thread. See the docs of the Worker for more information.
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 prepare the Worker using a slightly modified snippet from the previous blog post:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
const JSZip = require('jszip'); onmessage = (e) => { downloadAndExtractZipFile(e.data.url) .then(files => postMessage(files)) .catch(error => console.error(error)); } async function downloadAndExtractZipFile(url) { const response = await fetch(url); const archive = await response.arrayBuffer(); const result = (await JSZip.loadAsync(archive)).filter((path, entry) => !entry.dir); const files = []; for (const file of result) { const contents = await file.async('text'); files.push({path: file.name, contents}); } return files; } |
The Worker will download and extract an archive file on a background thread after it’s done file paths, and their contents will be returned to the main thread. To keep it as simple as possible, we will just print the file paths and contents to the console.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
const worker = new Worker('script/worker.js'); worker.onmessage = (event) => { event.data.forEach(({path, contents}) => { console.log('Path:\n', path, '\nContents:\n', contents, '\n') }); worker.terminate(); } worker.onerror = (error) => { console.error(error); worker.terminate(); } worker.postMessage({url: 'https://tabris.com/wp-content/uploads/2020/07/zipfile.zip'}); /** * Path: * a folder/message.txt * Contents: * Hello world! * * Path: * another-message.txt * Contents: * Hello earth! */ |
That’s it!
The full code of the example is available here.
Fiddle with this example and run it in the Tabris.js developer app (Android/iOS) now:
Feedback is welcome!
Want to join the discussion?Feel free to contribute!