-
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy path6-metasync.js
More file actions
57 lines (46 loc) · 1.21 KB
/
6-metasync.js
File metadata and controls
57 lines (46 loc) · 1.21 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
'use strict';
const fs = require('node:fs');
// Production implementation from Metasync library
// See: https://github.com/metarhia/metasync
function Memoized() {}
const memoize = (fn) => {
const cache = new Map();
const memoized = function(...args) {
const callback = args.pop();
const key = args[0];
const record = cache.get(key);
if (record) {
console.log('Read from cache');
callback(record.err, record.data);
return;
}
fn(...args, (err, data) => {
cache.set(key, { err, data });
callback(err, data);
});
};
const fields = {
cache,
timeout: 0,
limit: 0,
size: 0,
maxSize: 0,
};
Object.setPrototypeOf(memoized, Memoized.prototype);
return Object.assign(memoized, fields);
};
Memoized.prototype.clear = function() {
this.cache.clear();
};
// Usage
fs.readFile = memoize(fs.readFile);
fs.readFile('6-metasync.js', 'utf8', (err, data) => {
console.log('data length:', data.length);
fs.readFile('6-metasync.js', 'utf8', (err, data) => {
console.log('data length:', data.length);
fs.readFile.clear();
fs.readFile('6-metasync.js', 'utf8', (err, data) => {
console.log('data length:', data.length);
});
});
});