Skip to content

Commit 57a2aaf

Browse files
authored
Create worker.js
1 parent 25e5f69 commit 57a2aaf

1 file changed

Lines changed: 77 additions & 0 deletions

File tree

worker.js

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
self.onmessage = async (e) => {
2+
try {
3+
const { action, id, data, extension } = e.data;
4+
let result;
5+
6+
switch (action) {
7+
case 'encode':
8+
result = await encodeFile(id, data, extension);
9+
break;
10+
case 'decode':
11+
result = await decodeFile(id, extension);
12+
break;
13+
case 'delete':
14+
result = await deleteFile(id);
15+
break;
16+
default:
17+
throw new Error('Invalid action');
18+
}
19+
20+
postMessage(result);
21+
} catch (error) {
22+
postMessage({
23+
action: 'error',
24+
error: error.message,
25+
stack: error.stack
26+
});
27+
}
28+
};
29+
30+
async function encodeFile(id, data, extension) {
31+
const root = await navigator.storage.getDirectory();
32+
const filename = `${id}.${extension}`;
33+
const fileHandle = await root.getFileHandle(filename, { create: true });
34+
const accessHandle = await fileHandle.createSyncAccessHandle();
35+
36+
try {
37+
accessHandle.truncate(0);
38+
accessHandle.write(data);
39+
accessHandle.flush();
40+
return {
41+
action: 'encoded',
42+
id,
43+
filename,
44+
size: data.byteLength
45+
};
46+
} finally {
47+
accessHandle.close();
48+
}
49+
}
50+
51+
async function decodeFile(id, extension) {
52+
const root = await navigator.storage.getDirectory();
53+
const filename = `${id}.${extension}`;
54+
const fileHandle = await root.getFileHandle(filename);
55+
const accessHandle = await fileHandle.createSyncAccessHandle();
56+
57+
try {
58+
const size = accessHandle.getSize();
59+
const buffer = new Uint8Array(size);
60+
accessHandle.read(buffer);
61+
return {
62+
action: 'decoded',
63+
id,
64+
data: buffer.buffer,
65+
extension,
66+
size
67+
};
68+
} finally {
69+
accessHandle.close();
70+
}
71+
}
72+
73+
async function deleteFile(id) {
74+
const root = await navigator.storage.getDirectory();
75+
await root.removeEntry(id);
76+
return { action: 'deleted', id };
77+
}

0 commit comments

Comments
 (0)