-
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy path4-async.js
More file actions
42 lines (37 loc) · 1002 Bytes
/
4-async.js
File metadata and controls
42 lines (37 loc) · 1002 Bytes
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
'use strict';
const fs = require('node:fs');
// args[0] - key
// args[args.length-1] - callback
const memoizeAsync = (lib, fnName) => {
const fn = lib[fnName];
const cache = {};
console.log('override', fnName);
lib[fnName] = (...args) => {
console.dir({ call: fnName, args, cache });
const cb = args.pop();
const key = args[0];
const record = cache[key];
console.log('key:', key);
console.log('cached:', record);
if (record) {
console.log('from cache');
cb(record.err, record.data);
return;
}
fn(...args, (err, data) => {
console.log('from file');
console.log('Save key:', key);
cache[key] = { err, data };
console.dir({ cache });
cb(err, data);
});
};
};
// Usage
memoizeAsync(fs, 'readFile');
fs.readFile('4-async.js', 'utf8', (err, data) => {
console.log('data length:', data.length);
fs.readFile('4-async.js', 'utf8', (err, data) => {
console.log('data length:', data.length);
});
});