-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3-io.js
More file actions
59 lines (46 loc) · 1.04 KB
/
3-io.js
File metadata and controls
59 lines (46 loc) · 1.04 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
'use strict';
class Reactor {
#tasks = [];
#active = false;
enqueue(fn) {
this.#tasks.push(fn);
}
start() {
this.#active = true;
while (this.#active && this.#tasks.length) {
const tasks = this.#tasks.splice(0);
for (const fn of tasks) fn();
}
}
stop() {
this.#tasks.splice(0);
this.#active = false;
}
get active() {
return this.#active;
}
}
const eventLoop = new Reactor();
// File system
const { readFileSync } = require('node:fs');
const readFile = (path, encoding, callback) => {
const read = () => {
try {
const data = readFileSync(path, encoding);
callback(null, data);
} catch (err) {
callback(err);
}
};
eventLoop.enqueue(read);
};
// Usage
readFile('./3-io.js', 'utf8', (err, data) => {
if (err) console.error('Error:', err.message);
else console.log('File contents:', data);
});
readFile('./unknown.txt', 'utf8', (err, data) => {
if (err) console.error('Error:', err.message);
else console.log('File contents:', data);
});
eventLoop.start();