-
Notifications
You must be signed in to change notification settings - Fork 14
/
archive_utils.ts
55 lines (44 loc) · 1.45 KB
/
archive_utils.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
import { existsSync, lstatSync } from "fs";
import { lstat } from "fs/promises";
import { glob } from "glob";
import path from "path";
const archiver = require("archiver");
const { createWriteStream } = require("fs");
export async function zipFolder(
inputDirectory: string,
outputArchive: string,
subdirectory: string | boolean = false
): Promise<any> {
return new Promise((resolve, reject) => {
const output = createWriteStream(outputArchive);
output.on('close', () => {
resolve(true)
});
const archive = archiver('zip');
archive.on('error', (err: any) => {
reject(err);
});
archive.pipe(output);
if (existsSync(inputDirectory)) {
archive.directory(inputDirectory, subdirectory);
}
archive.finalize();
});
}
export async function zipIfFolder(
inputPath: string,
): Promise<string> {
return new Promise(async (resolve, reject) => {
const paths = glob.sync(inputPath);
if (paths.length === 0) throw new Error(`Could not find file matching pattern: ${inputPath}`);
const stat = await lstat(paths[0]);
if (stat.isDirectory()) {
const basename = path.basename(paths[0]);
const archiveName = basename + '.zip';
await zipFolder(paths[0], archiveName, basename);
resolve(archiveName);
} else {
resolve(paths[0]);
}
});
}