-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
72 lines (58 loc) · 1.52 KB
/
mod.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
// Copyright 2021 Kirill Reunov. All rights reserved. MIT license.
/**
* Deno FastWriter ✒
* Fast & Safe file writer for Deno!
*/
export class FastWriter {
/** Next data for writing. */
private next: string | null;
/** Lock writing. */
private locked: boolean;
/** Path to the file. */
private readonly path: string;
/** Path to the temporary file. */
private readonly temp: string;
/**
* Fast Writer initialization.
* @param path Path to the file.
*/
constructor(path: string) {
this.path = path;
this.temp = this.path + '.temp';
this.next = null;
this.locked = false;
}
/**
* Write data to the file.
* @param data Data to write.
*/
public write(data: string): void {
this._write(data);
}
/**
* Main writing method.
* @param data Data to write.
*/
private async _write(data: string): Promise<void> {
// Add data to the queue if writer is locked
if (this.locked) {
this.next = data;
return;
}
// Lock writing
this.locked = true;
try {
// Atomic writing
await Deno.writeTextFile(this.temp, data);
await Deno.rename(this.temp, this.path);
} finally {
this.locked = false;
}
// Start next writing
if (this.next) {
const nextData = this.next;
this.next = null;
this._write(nextData);
}
}
}