Skip to content

Instantly share code, notes, and snippets.

@mfbx9da4
Created January 28, 2021 15:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mfbx9da4/b60edd7143a386c2f4be49b57eb5445b to your computer and use it in GitHub Desktop.
Save mfbx9da4/b60edd7143a386c2f4be49b57eb5445b to your computer and use it in GitHub Desktop.
Acquire a lock across processes using the file system
const fs = require("fs");
const acquireLock = async (identifier, retries = 5, delay = 1000) => {
const pathname = `${identifier}.lock`;
const acquire = () => {
try {
fs.mkdirSync(pathname);
return true;
} catch {}
};
const release = () => fs.rmdirSync(pathname);
for (let i = 0; i < retries; i++) {
if (acquire()) return release;
await new Promise((r) => setTimeout(r, delay));
}
};
const usage = async () => {
const lock = await acquireLock("asdf");
if (lock) {
console.log("got the lock!");
lock();
} else {
console.log("failed to get the lock!");
}
};
usage();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment