Created
May 15, 2021 15:45
-
-
Save kissarat/e74110e0f8b2186d2c67f8d1d31550f1 to your computer and use it in GitHub Desktop.
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 { 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