diff --git a/src/node-to-fsa/NodeFileSystemSyncAccessHandle.ts b/src/node-to-fsa/NodeFileSystemSyncAccessHandle.ts index 4abb2220e..28a90e81e 100644 --- a/src/node-to-fsa/NodeFileSystemSyncAccessHandle.ts +++ b/src/node-to-fsa/NodeFileSystemSyncAccessHandle.ts @@ -40,8 +40,20 @@ export class NodeFileSystemSyncAccessHandle { */ public async read(buffer: ArrayBuffer | ArrayBufferView, options: FileSystemReadWriteOptions = {}): Promise { 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; + } } } diff --git a/src/node-to-fsa/__tests__/NodeFileSystemSyncAccessHandle.test.ts b/src/node-to-fsa/__tests__/NodeFileSystemSyncAccessHandle.test.ts index 7932b3e6e..9db6c161d 100644 --- a/src/node-to-fsa/__tests__/NodeFileSystemSyncAccessHandle.test.ts +++ b/src/node-to-fsa/__tests__/NodeFileSystemSyncAccessHandle.test.ts @@ -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'); + } + }); }); });