diff --git a/src/index.ts b/src/index.ts index 0b9e26f6..68ca4408 100644 --- a/src/index.ts +++ b/src/index.ts @@ -46,9 +46,21 @@ export const open = async ( persistent: opts.watchForUpdatesNonPersistent !== true, }; - fs.watchFile(filepath, watcherOptions, async (curr, prev) => { - // Make sure file was modified, not just accessed - if (!curr || prev && prev.mtimeMs === curr.mtimeMs) { + 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())) { return; } const updatedDatabase = await fs.readFile(filepath);