-
Notifications
You must be signed in to change notification settings - Fork 306
Expand file tree
/
Copy pathlock.js
More file actions
31 lines (28 loc) · 901 Bytes
/
lock.js
File metadata and controls
31 lines (28 loc) · 901 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const { lock } = require('proper-lockfile')
const staleSeconds = 30
// Obtains a lock on the path, and maintains it until the callback finishes
function withLock (path, options = {}, callback = options) {
return new Promise(async (resolve, reject) => {
let releaseLock, result
try {
// Obtain the lock
releaseLock = await lock(path, {
retries: 10,
update: 1000,
stale: staleSeconds * 1000,
realpath: !!options.mustExist,
onCompromised: () =>
reject(new Error(`The file at ${path} was not updated within ${staleSeconds}s.`))
})
// Hold on to the lock until the callback's returned promise resolves
result = await callback()
} catch (error) {
reject(error)
// Ensure the lock is always released
} finally {
await releaseLock()
}
resolve(result)
})
}
module.exports = withLock