Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(volume): toJSON now accepts the asBuffer parameter #952

Merged
merged 1 commit into from
Sep 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/__tests__/volume.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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])', () => {
Expand Down
8 changes: 4 additions & 4 deletions src/volume.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);
}
Expand All @@ -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) {
Expand All @@ -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;
}

Expand Down