Created
January 28, 2021 15:24
-
-
Save mfbx9da4/b60edd7143a386c2f4be49b57eb5445b to your computer and use it in GitHub Desktop.
Acquire a lock across processes using the file system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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