From 7adff27ebd7d455efea7d25b988a01a0d6e4e0c6 Mon Sep 17 00:00:00 2001 From: Vadim Dalecky Date: Thu, 15 Jun 2023 02:15:00 +0200 Subject: [PATCH] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20throw=20exception=20on?= =?UTF-8?q?=20closed=20files?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../NodeFileSystemSyncAccessHandle.ts | 16 ++++++++++++++-- .../NodeFileSystemSyncAccessHandle.test.ts | 17 +++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) 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'); + } + }); }); });