Skip to content

Commit

Permalink
Reload db when it was actually modified (#850)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
frenzzy authored Oct 1, 2024
1 parent 8d9c29c commit 2ad9051
Showing 1 changed file with 3 additions and 15 deletions.
18 changes: 3 additions & 15 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,21 +46,9 @@ export const open = async <T extends Response>(
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);
Expand Down

0 comments on commit 2ad9051

Please sign in to comment.