-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfs.mjs
55 lines (55 loc) · 1.74 KB
/
fs.mjs
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
import fs from 'fs';
import util from 'util';
const promisify = util.promisify;
const exports = Object.create(fs, {
readFile: {
configurable: true,
enumerable: true,
writable: true,
value: function readFile(...args) {
exports.readFile = wrap(fs.readFile, args => console.log('fs.readFile called'));
return passThrough(exports.readFile, this, args, new.target);
},
},
});
export default exports;
// Generic function to execute things before another
// if the function is intended to be promisified
// it will add util.promisify.custom
//
// @param {Function} fn - the function we want to insert behavior around
// @param {Function} before - the function to invoke before `fn`
// @param {Boolean} promisified - if `fn` has promisified behavior
// @return {Function}
function wrap(fn, before, promisified = false) {
const wrapped = function() {
before(arguments, this, new.target);
passThrough(fn, this, arguments, new.target);
};
if (promisified === true) {
Object.defineProperty(wrapped, promisify.custom, {
configurable: true,
get() {
const promisified = promisify(fn);
Object.defineProperty(wrapped, promisify.custom, {
configurable: true,
value: wrap(promisified, before, false),
});
return value;
},
});
}
return wrapped;
}
// Invokes or constructs a function depending on if it had a new.target
//
// @param {Function} fn
// @param {any} self - the `this` value provided
// @param {any[]} args - the `arguments` value provided
// @param {any} target - the `new.target` value provided
// @returns {any}
function passThrough(fn, self, args, target) {
return target
? Reflect.construct(fn, args, target)
: Reflect.apply(fn, self, args);
}