/
packer.ts
84 lines (69 loc) · 3.07 KB
/
packer.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
76
77
78
79
80
81
82
83
84
import { Stream } from "stream";
import { File } from "@file/file";
import { Compiler } from "./next-compiler";
/**
* Use blanks to prettify
*/
export const PrettifyType = {
NONE: "",
WITH_2_BLANKS: " ",
WITH_4_BLANKS: " ",
// eslint-disable-next-line @typescript-eslint/naming-convention
WITH_TAB: "\t",
} as const;
const convertPrettifyType = (
prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType],
): (typeof PrettifyType)[keyof typeof PrettifyType] | undefined =>
prettify === true ? PrettifyType.WITH_2_BLANKS : prettify === false ? undefined : prettify;
export class Packer {
public static async toString(file: File, prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType]): Promise<string> {
const zip = this.compiler.compile(file, convertPrettifyType(prettify));
const zipData = await zip.generateAsync({
type: "string",
mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
compression: "DEFLATE",
});
return zipData;
}
public static async toBuffer(file: File, prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType]): Promise<Buffer> {
const zip = this.compiler.compile(file, convertPrettifyType(prettify));
const zipData = await zip.generateAsync({
type: "nodebuffer",
mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
compression: "DEFLATE",
});
return zipData;
}
public static async toBase64String(file: File, prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType]): Promise<string> {
const zip = this.compiler.compile(file, convertPrettifyType(prettify));
const zipData = await zip.generateAsync({
type: "base64",
mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
compression: "DEFLATE",
});
return zipData;
}
public static async toBlob(file: File, prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType]): Promise<Blob> {
const zip = this.compiler.compile(file, convertPrettifyType(prettify));
const zipData = await zip.generateAsync({
type: "blob",
mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
compression: "DEFLATE",
});
return zipData;
}
public static toStream(file: File, prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType]): Stream {
const stream = new Stream();
const zip = this.compiler.compile(file, convertPrettifyType(prettify));
zip.generateAsync({
type: "nodebuffer",
mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
compression: "DEFLATE",
}).then((z) => {
stream.emit("data", z);
stream.emit("end");
});
return stream;
}
private static readonly compiler = new Compiler();
}