Skip to content

Instantly share code, notes, and snippets.

@kissarat
Created May 15, 2021 15:45
Show Gist options
  • Save kissarat/e74110e0f8b2186d2c67f8d1d31550f1 to your computer and use it in GitHub Desktop.
Save kissarat/e74110e0f8b2186d2c67f8d1d31550f1 to your computer and use it in GitHub Desktop.
const { promises: { stat, writeFile, unlink } } = require('fs')
const { settings } = require('./settings')
class LockError extends Error {
constructor(name, message) {
super(message || `Already locked by ${name}`)
this.name = name
}
}
async function fileLock(lockFile = settings.lockFile()) {
if (lockFile) {
try {
await stat(lockFile)
throw new LockError(lockFile)
} catch (err) {
if ('ENOENT' === err.code) {
await writeFile(lockFile, (process.pid).toString(), 'utf8');
// console.log(`Lock file ${lockFile} created`)
} else {
throw err;
}
}
}
}
async function fileUnlock(lockFile = settings.lockFile()) {
if (lockFile) {
try {
await unlink(lockFile)
} catch (err) {
if ('ENOENT' === err.code) {
console.error(`Lock file ${lockFile} does not exists`)
}
}
}
}
module.exports = { fileLock, fileUnlock, LockError }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment