proper-lockfile is a robust JavaScript utility for managing inter-process and inter-machine file locks across local and network file systems. Currently at version 4.1.2, it is actively maintained with updates released as needed. Its core design uses an atomic `mkdir` strategy for lockfile creation, which is more reliable than `open` with `O_EXCL` flags, especially on network file systems (NFS) where `O_EXCL` is prone to race conditions. The library differentiates itself by constantly updating the lockfile's `mtime` (modified time) to accurately check for staleness, a significant improvement over `ctime` (creation time) for long-running processes. Furthermore, it incorporates mechanisms to detect when a lockfile might be compromised due to failed updates or unexpected delays, enhancing overall reliability compared to alternatives.
npm install proper-lockfileVerified import paths — ran on the pinned version, not inferred.
Demonstrates how to acquire, use, and release an inter-process lock on a file using asynchronous functions, including error handling and retry options. It also shows basic file system interaction.
Ensure consistent `stale` and `update` options are used for a given lockable file across all processes accessing it. Store these values in a shared configuration.
Avoid direct manipulation of `.lock` files. Always use the library's `release()` or `unlock()` functions. Implement robust error handling for `onCompromised` callbacks.
Always `await` or `.catch()` the promise returned by the `release()` function and implement appropriate error recovery or logging.
Adjust the `stale` option according to the expected maximum duration of the critical section and the network/filesystem characteristics. The `update` interval (default `stale/2`) should also be considered.
Handle the `ELOCKED` error code (if available) or the general error by implementing retry logic with exponential backoff or waiting for the lock to be released. Configure the `retries` option for `lock()`.
Implement robust error handling in the `onCompromised` callback and for the `release()` promise. This usually indicates a critical state requiring process termination or immediate re-evaluation of resource access.
Ensure the target file you intend to lock exists before calling `lock()` or `check()`. Use `fs.promises.writeFile(filePath, '', { flag: 'a+' })` to create it if it doesn't exist.