From c4da142211c96a77df169d2789efcc7e6b9dd802 Mon Sep 17 00:00:00 2001 From: Stanley Horwood Date: Tue, 14 Feb 2023 21:45:08 +0100 Subject: [PATCH] feat(volume): `toJSON` now accepts the `asBuffer` parameter `vol.toJSON` can now output the virtual directory structure as a map of `Buffer` if the `asBuffer` parameter is set to `true`. The default behavior is still to output a map of `utf8` strings. --- src/__tests__/volume.test.ts | 8 ++++++++ src/volume.ts | 8 ++++---- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/__tests__/volume.test.ts b/src/__tests__/volume.test.ts index 7053715c7..8dae765f2 100644 --- a/src/__tests__/volume.test.ts +++ b/src/__tests__/volume.test.ts @@ -187,6 +187,14 @@ describe('volume', () => { '/empty': null, }); }); + + it('Outputs files as buffers if the option is set', () => { + const buffer = Buffer.from('Hello'); + const vol = new Volume(); + vol.writeFileSync('/file', buffer); + const result = vol.toJSON('/', {}, false, true)['/file']; + expect(result).toStrictEqual(buffer); + }); }); describe('.fromJSON(json[, cwd])', () => { diff --git a/src/volume.ts b/src/volume.ts index e77ef17a4..1492af810 100644 --- a/src/volume.ts +++ b/src/volume.ts @@ -524,7 +524,7 @@ export class Volume implements FsCallbackApi { }); } - private _toJSON(link = this.root, json = {}, path?: string): DirectoryJSON { + private _toJSON(link = this.root, json = {}, path?: string, asBuffer?: boolean): DirectoryJSON { let isEmpty = true; let children = link.children; @@ -549,7 +549,7 @@ export class Volume implements FsCallbackApi { if (node.isFile()) { let filename = child.getPath(); if (path) filename = relative(path, filename); - json[filename] = node.getString(); + json[filename] = asBuffer ? node.getBuffer() : node.getString(); } else if (node.isDirectory()) { this._toJSON(child, json, path); } @@ -566,7 +566,7 @@ export class Volume implements FsCallbackApi { return json; } - toJSON(paths?: PathLike | PathLike[], json = {}, isRelative = false): DirectoryJSON { + toJSON(paths?: PathLike | PathLike[], json = {}, isRelative = false, asBuffer = false): DirectoryJSON { const links: Link[] = []; if (paths) { @@ -582,7 +582,7 @@ export class Volume implements FsCallbackApi { } if (!links.length) return json; - for (const link of links) this._toJSON(link, json, isRelative ? link.getPath() : ''); + for (const link of links) this._toJSON(link, json, isRelative ? link.getPath() : '', asBuffer); return json; }