-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
77 lines (70 loc) · 2.06 KB
/
worker.js
File metadata and controls
77 lines (70 loc) · 2.06 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
self.onmessage = async (e) => {
try {
const { action, id, data, extension } = e.data;
let result;
switch (action) {
case 'encode':
result = await encodeFile(id, data, extension);
break;
case 'decode':
result = await decodeFile(id, extension);
break;
case 'delete':
result = await deleteFile(id);
break;
default:
throw new Error('Invalid action');
}
postMessage(result);
} catch (error) {
postMessage({
action: 'error',
error: error.message,
stack: error.stack
});
}
};
async function encodeFile(id, data, extension) {
const root = await navigator.storage.getDirectory();
const filename = `${id}.${extension}`;
const fileHandle = await root.getFileHandle(filename, { create: true });
const accessHandle = await fileHandle.createSyncAccessHandle();
try {
accessHandle.truncate(0);
accessHandle.write(data);
accessHandle.flush();
return {
action: 'encoded',
id,
filename,
size: data.byteLength
};
} finally {
accessHandle.close();
}
}
async function decodeFile(id, extension) {
const root = await navigator.storage.getDirectory();
const filename = `${id}.${extension}`;
const fileHandle = await root.getFileHandle(filename);
const accessHandle = await fileHandle.createSyncAccessHandle();
try {
const size = accessHandle.getSize();
const buffer = new Uint8Array(size);
accessHandle.read(buffer);
return {
action: 'decoded',
id,
data: buffer.buffer,
extension,
size
};
} finally {
accessHandle.close();
}
}
async function deleteFile(id) {
const root = await navigator.storage.getDirectory();
await root.removeEntry(id);
return { action: 'deleted', id };
}