Skip to content

Commit 182ea8b

Browse files
authored
feat: support promises in patchFs (#217)
1 parent e774439 commit 182ea8b

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

docs/api/patchFs.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,14 @@ vol.fromJSON({'/dir/foo': 'bar'});
2727
patchFs(vol);
2828
console.log(require('fs').readdirSync('/')); // [ 'dir' ]
2929
```
30+
31+
Promises API is supported as well:
32+
33+
```js
34+
import {vol} from 'memfs';
35+
import {patchFs} from 'fs-monkey';
36+
37+
vol.fromJSON({'/dir/foo': 'bar'});
38+
patchFs(vol);
39+
require('fs').promises.readFile('/dir/foo', 'UTF-8').then(console.log); // bar
40+
```

src/__tests__/patchFs.test.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,29 @@ describe('patchFs', () => {
2020
expect(fs.F_OK).toBe(vol.F_OK);
2121
});
2222

23+
it('should patch promises', () => {
24+
const vol = {
25+
get promises() {
26+
return {
27+
readFile: () => 'foo'
28+
}
29+
}
30+
};
31+
const fs = {
32+
get promises() {
33+
return {
34+
readFile: () => 'bar'
35+
}
36+
}
37+
};
38+
39+
const unpatch = patchFs(vol, fs);
40+
expect(fs.promises.readFile()).toBe('foo');
41+
42+
unpatch();
43+
expect(fs.promises.readFile()).toBe('bar');
44+
})
45+
2346
describe('unpatch()', () => {
2447
it('should return "unpatch" method', () => {
2548
const vol = {

src/patchFs.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,24 @@ export default function patchFs(vol, fs = require('fs')) {
4848
if(typeof vol[method] === 'function')
4949
patchMethod(method);
5050

51+
// Promises API
52+
let promisesBackup;
53+
try {
54+
promisesBackup = fs.promises;
55+
Object.defineProperty(fs, 'promises', {
56+
get: () => vol.promises
57+
});
58+
} catch {
59+
undefined;
60+
}
61+
5162
// Give user back a method to revert the changes.
5263
return function unpatch () {
5364
for (const key in bkp) fs[key] = bkp[key];
65+
if (promisesBackup) {
66+
Object.defineProperty(fs, 'promises', {
67+
get: () => promisesBackup
68+
});
69+
}
5470
};
5571
};

0 commit comments

Comments
 (0)