Skip to content

Commit

Permalink
feat: 🎸 implement read() method
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Jun 17, 2023
1 parent d818f16 commit 7357c14
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/fsa-to-node/FsaNodeFs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,22 @@ export class FsaNodeFs implements FsCallbackApi, FsCommonObjects {
position: number,
callback: (err?: Error | null, bytesRead?: number, buffer?: Buffer | ArrayBufferView | DataView) => void,
): void => {
throw new Error('Not implemented');
validateCallback(callback);
// This `if` branch is from Node.js
if (length === 0) {
return process.nextTick(() => {
if (callback) callback(null, 0, buffer);
});
}
(async () => {
const openFile = await this.getFileByFd(fd, 'read');
const file = await openFile.file.getFile();
const src = await file.arrayBuffer();
const slice = new Uint8Array(src, Number(position), Number(length));
const dest = new Uint8Array(buffer.buffer, buffer.byteOffset + offset, slice.length);
dest.set(slice, 0);
return slice.length;
})().then((bytesWritten) => callback(null, bytesWritten, buffer), error => callback(error));
};

public readonly readFile: FsCallbackApi['readFile'] = (
Expand Down
31 changes: 31 additions & 0 deletions src/fsa-to-node/__tests__/FsaNodeFs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -579,3 +579,34 @@ describe('.writeFile()', () => {
});
});
});

describe('.read()', () => {
test('can read from a file at offset into Buffer', async () => {
const { fs } = setup({ folder: { file: 'test' }, 'empty-folder': null, 'f.html': 'test' });
const handle = await fs.promises.open('/folder/file', 'r');
const [buffer, length] = await new Promise<[Buffer, number]>((resolve, reject) => {
const buffer = Buffer.alloc(4);
fs.read(handle.fd, buffer, 0, 2, 1, (error, bytesRead, buffer) => {
if (error) reject(error);
else resolve([buffer as Buffer, bytesRead!]);
});
});
expect(length).toBe(2);
expect(buffer.slice(0, 2).toString()).toBe('es');
});

test('can read from a file at offset into Uint8Array', async () => {
const { fs } = setup({ folder: { file: 'test' }, 'empty-folder': null, 'f.html': 'test' });
const handle = await fs.promises.open('/folder/file', 'r');
const [buffer, length] = await new Promise<[Buffer, number]>((resolve, reject) => {
const buffer = new Uint8Array(4);
fs.read(handle.fd, buffer, 0, 2, 1, (error, bytesRead, buffer) => {
if (error) reject(error);
else resolve([buffer as Buffer, bytesRead!]);
});
});
expect(length).toBe(2);
expect(buffer[0]).toBe(101);
expect(buffer[1]).toBe(115);
});
});

0 comments on commit 7357c14

Please sign in to comment.