forked from exceptionless/Exceptionless.JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNodeDirectoryStorage.ts
More file actions
66 lines (54 loc) · 1.6 KB
/
NodeDirectoryStorage.ts
File metadata and controls
66 lines (54 loc) · 1.6 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
import { mkdirSync } from "fs";
import { readdir, readFile, unlink, writeFile } from "fs/promises";
import { dirname, join, resolve } from "path";
import { argv } from "process";
export class NodeDirectoryStorage {
private directory: string;
constructor(directory?: string) {
if (!directory) {
this.directory = argv && argv.length > 1 ? join(dirname(argv[1]), ".exceptionless") : ".exceptionless";
} else {
this.directory = resolve(directory);
}
mkdirSync(this.directory, { recursive: true });
}
public async length(): Promise<number> {
const keys = await this.keys();
return keys.length;
}
public async clear(): Promise<void> {
for (const key of await this.keys()) {
await this.removeItem(key);
}
return Promise.resolve();
}
public async getItem(key: string): Promise<string | null> {
try {
return await readFile(join(this.directory, key), "utf8");
} catch (ex) {
if (ex.code === "ENOENT") {
return null;
}
throw ex;
}
}
public async key(index: number): Promise<string | null> {
const keys = await this.keys();
return Promise.resolve(index < keys.length ? keys[index] : null);
}
public async keys(): Promise<string[]> {
return await readdir(this.directory);
}
public async removeItem(key: string): Promise<void> {
try {
await unlink(join(this.directory, key));
} catch (ex) {
if (ex.code !== "ENOENT") {
throw ex;
}
}
}
public async setItem(key: string, value: string): Promise<void> {
await writeFile(join(this.directory, key), value);
}
}