Skip to content

Commit

Permalink
feat: 🎸 throw exception on closed files
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Jun 20, 2023
1 parent f9b0f73 commit 7adff27
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/node-to-fsa/NodeFileSystemSyncAccessHandle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,20 @@ export class NodeFileSystemSyncAccessHandle {
*/
public async read(buffer: ArrayBuffer | ArrayBufferView, options: FileSystemReadWriteOptions = {}): Promise<number> {
const buf: Buffer | ArrayBufferView = buffer instanceof ArrayBuffer ? Buffer.from(buffer) : buffer;
const size = this.fs.readSync(this.fd, buf, 0, buffer.byteLength, options.at || 0);
return size;
try {
const size = this.fs.readSync(this.fd, buf, 0, buffer.byteLength, options.at || 0);
return size;
} catch (error) {
if (error instanceof DOMException) throw error;
if (error && typeof error === 'object') {
switch (error.code) {
case 'EBADF': {
throw new DOMException('File handle already closed.', 'InvalidStateError');
}
}
}
throw error;
}
}
}

Expand Down
17 changes: 17 additions & 0 deletions src/node-to-fsa/__tests__/NodeFileSystemSyncAccessHandle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,5 +94,22 @@ maybe('NodeFileSystemSyncAccessHandle', () => {
expect(size).toBe(10);
expect(Buffer.from(buf).slice(0, 10).toString()).toBe('0123456789');
});

test('throws "InvalidStateError" DOMException if handle is closed', async () => {
const { dir } = setup({
'file.txt': '0123456789',
});
const entry = await dir.getFileHandle('file.txt');
const sync = await entry.createSyncAccessHandle!();
await sync.close();
const buf = new Uint8Array(25);
try {
const size = await sync.read(buf);
throw new Error('No error was thrown');
} catch (error) {
expect(error).toBeInstanceOf(DOMException);
expect(error.name).toBe('InvalidStateError');
}
});
});
});

0 comments on commit 7adff27

Please sign in to comment.