-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
75 lines (70 loc) · 1.87 KB
/
index.ts
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
import type { Readable } from 'node:stream';
import compressing from 'compressing';
import {
fileTypeFromBuffer,
fileTypeFromFile,
fileTypeFromStream,
} from 'file-type';
import { removeExtension } from './utils.js';
export async function unarchive(
input: string | Buffer | NodeJS.ReadableStream,
dest?: string,
) {
const type = await getFileType(input);
if (!dest) {
if (typeof input === 'string') {
dest ||= removeExtension(input);
} else {
throw new Error(
'Destination path is required for streams or buffers',
);
}
}
switch (type?.ext) {
case 'tar':
await compressing.tar.uncompress(
input as compressing.sourceType,
dest,
);
break;
case 'gz':
await compressing.tgz.uncompress(
input as compressing.sourceType,
dest,
);
break;
// biome-ignore lint/complexity/noUselessSwitchCase: for clarity
case 'zip':
default:
try {
await compressing.zip.uncompress(
input as compressing.sourceType,
dest,
);
} catch (e) {
console.error(e);
throw new Error(`Unknown file type for ${input}`);
}
}
}
async function getFileType(
input:
| string
| Uint8Array
| ArrayBuffer
| Buffer
| Readable
| NodeJS.ReadableStream,
) {
if (typeof input === 'string') {
return fileTypeFromFile(input);
}
if (
input instanceof Uint8Array ||
input instanceof ArrayBuffer ||
input instanceof Buffer
) {
return fileTypeFromBuffer(input);
}
return fileTypeFromStream(input as Readable);
}