From 2ad905164cc03d7893730791c41ca0c7ceef2bfe Mon Sep 17 00:00:00 2001 From: Vladimir Kutepov Date: Tue, 1 Oct 2024 08:46:49 +0700 Subject: [PATCH] Reload db when it was actually modified (#850) * 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`. * fix tests attempt --- src/index.ts | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/src/index.ts b/src/index.ts index 68ca4408..0b9e26f6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -46,21 +46,9 @@ export const open = async ( persistent: opts.watchForUpdatesNonPersistent !== true, }; - fs.watchFile(filepath, watcherOptions, async () => { - // 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())) { + fs.watchFile(filepath, watcherOptions, async (curr, prev) => { + // Make sure file was modified, not just accessed + if (!curr || prev && prev.mtimeMs === curr.mtimeMs) { return; } const updatedDatabase = await fs.readFile(filepath);