From 55651f440422d628e73ef2e9a45345f6a911d142 Mon Sep 17 00:00:00 2001 From: Leo Liang Date: Tue, 9 Feb 2021 11:20:47 +0000 Subject: [PATCH] Support promises in patchFs --- docs/api/patchFs.md | 11 +++++++++++ src/__tests__/patchFs.test.js | 23 +++++++++++++++++++++++ src/patchFs.js | 16 ++++++++++++++++ 3 files changed, 50 insertions(+) diff --git a/docs/api/patchFs.md b/docs/api/patchFs.md index e3475c59..740cfc17 100644 --- a/docs/api/patchFs.md +++ b/docs/api/patchFs.md @@ -27,3 +27,14 @@ vol.fromJSON({'/dir/foo': 'bar'}); patchFs(vol); console.log(require('fs').readdirSync('/')); // [ 'dir' ] ``` + +Promises API is supported as well: + +```js +import {vol} from 'memfs'; +import {patchFs} from 'fs-monkey'; + +vol.fromJSON({'/dir/foo': 'bar'}); +patchFs(vol); +require('fs').promises.readFile('/dir/foo', 'UTF-8').then(console.log); // bar +``` diff --git a/src/__tests__/patchFs.test.js b/src/__tests__/patchFs.test.js index b6f5303f..94f23f13 100644 --- a/src/__tests__/patchFs.test.js +++ b/src/__tests__/patchFs.test.js @@ -20,6 +20,29 @@ describe('patchFs', () => { expect(fs.F_OK).toBe(vol.F_OK); }); + it('should patch promises', () => { + const vol = { + get promises() { + return { + readFile: () => 'foo' + } + } + }; + const fs = { + get promises() { + return { + readFile: () => 'bar' + } + } + }; + + const unpatch = patchFs(vol, fs); + expect(fs.promises.readFile()).toBe('foo'); + + unpatch(); + expect(fs.promises.readFile()).toBe('bar'); + }) + describe('unpatch()', () => { it('should return "unpatch" method', () => { const vol = { diff --git a/src/patchFs.js b/src/patchFs.js index 92357e83..1e664461 100644 --- a/src/patchFs.js +++ b/src/patchFs.js @@ -48,8 +48,24 @@ export default function patchFs(vol, fs = require('fs')) { if(typeof vol[method] === 'function') patchMethod(method); + // Promises API + let promisesBackup; + try { + promisesBackup = fs.promises; + Object.defineProperty(fs, 'promises', { + get: () => vol.promises + }); + } catch { + undefined; + } + // Give user back a method to revert the changes. return function unpatch () { for (const key in bkp) fs[key] = bkp[key]; + if (promisesBackup) { + Object.defineProperty(fs, 'promises', { + get: () => promisesBackup + }); + } }; };