-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path8-files-map.js
More file actions
73 lines (65 loc) · 1.73 KB
/
8-files-map.js
File metadata and controls
73 lines (65 loc) · 1.73 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
67
68
69
70
71
72
73
'use strict';
const fs = require('node:fs/promises');
const { Console } = require('node:console');
class Logger {
#files = new Map();
async use(filename) {
let instance = this.#files.get(filename);
if (!instance) {
instance = await Logger.#open(filename);
this.#files.set(filename, instance);
}
instance.count++;
console.log(`👉 Use: ${filename}`);
const disposable = Object.create(instance.console);
disposable[Symbol.asyncDispose] = async () => {
instance.count--;
console.log(`👉 Dispose: ${filename}`);
if (instance.count > 0) return;
console.log(`👉 Close: ${filename}`);
await instance.fd.close();
this.#files.delete(filename);
};
return disposable;
}
static async #open(filename) {
console.log(`👉 Open: ${filename}`);
const fd = await fs.open(filename, 'a');
const stream = fd.createWriteStream(filename, { flush: true });
const con = new Console({ stdout: stream });
return { count: 0, fd, console: con };
}
}
// Usage
const logger = new Logger();
const main = async () => {
// Block 0
await using console = await logger.use('output.log');
console.log('Log 0');
{
// Block 1
await using console = await logger.use('output.log');
console.log('Log 1');
}
{
// Block 2
await using console = await logger.use('output.log');
console.log('Log 2');
{
// Block 3
await using console = await logger.use('output3.log');
console.log('Log 3');
{
// Block 4
await using console = await logger.use('output.log');
console.log('Log 4');
}
}
}
return console;
};
main().then((ref) => {
// Block 5
console.log('After main');
ref.log('Log 5');
});