From 4c7b137562e4095e7f415b04fefb74a421c00457 Mon Sep 17 00:00:00 2001 From: Vladimir Kutepov Date: Wed, 3 Jul 2024 01:17:07 +0700 Subject: [PATCH 1/2] Reload db when it was actually modified [From Node.js documentation:](https://nodejs.org/docs/latest/api/fs.html#fswatchfilefilename-options-listener) > To be notified when the file was modified, not just accessed, it is necessary to compare `curr.mtimeMs` and `prev.mtimeMs`. --- src/index.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/index.ts b/src/index.ts index 68ca4408..63573e7a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -46,7 +46,11 @@ export const open = async ( persistent: opts.watchForUpdatesNonPersistent !== true, }; - fs.watchFile(filepath, watcherOptions, async () => { + fs.watchFile(filepath, watcherOptions, async (curr, prev) => { + // Make sure file was modified, not just accessed + if (curr.mtimeMs === prev.mtimeMs) { + return; + } // When database file is being replaced, // it could be removed for a fraction of a second. const waitExists = async () => { From 9a753438c61e55de9a2be59cdb1d7a7e8c8ddc6d Mon Sep 17 00:00:00 2001 From: Vladimir Kutepov Date: Thu, 4 Jul 2024 21:37:13 +0700 Subject: [PATCH 2/2] fix tests attempt --- src/index.ts | 18 +----------------- 1 file changed, 1 insertion(+), 17 deletions(-) diff --git a/src/index.ts b/src/index.ts index 63573e7a..0b9e26f6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -48,23 +48,7 @@ export const open = async ( fs.watchFile(filepath, watcherOptions, async (curr, prev) => { // Make sure file was modified, not just accessed - if (curr.mtimeMs === prev.mtimeMs) { - return; - } - // When database file is being replaced, - // it could be removed for a fraction of a second. - const waitExists = async () => { - for (let i = 0; i < 3; i++) { - if (fs.existsSync(filepath)) { - return true; - } - - await new Promise((a) => setTimeout(a, 500)); - } - - return false; - }; - if (!(await waitExists())) { + if (!curr || prev && prev.mtimeMs === curr.mtimeMs) { return; } const updatedDatabase = await fs.readFile(filepath);