96 lines
2.0 KiB
Markdown
96 lines
2.0 KiB
Markdown
# nlocks
|
|
|
|
A Node.js library providing asynchronous locking mechanisms including in-memory locks and file-based locks for coordinating access to resources across concurrent processes.
|
|
|
|
## Features
|
|
|
|
- **AsyncLock**: In-memory asynchronous lock for coordinating access to resources within a single process
|
|
- **FileLock**: File-based lock for coordinating access to resources across multiple processes
|
|
- Lightweight and easy to use
|
|
- Promise-based API
|
|
- Comprehensive test coverage
|
|
|
|
## Installation
|
|
|
|
```bash
|
|
npm install nlocks
|
|
```
|
|
|
|
## Usage
|
|
|
|
### Via index.js (recommended)
|
|
|
|
```javascript
|
|
const { AsyncLock, FileLock } = require('nlocks');
|
|
|
|
const asyncLock = new AsyncLock();
|
|
const fileLock = new FileLock();
|
|
```
|
|
|
|
### AsyncLock
|
|
|
|
An in-memory lock for synchronizing async operations within a single Node.js process:
|
|
|
|
```javascript
|
|
const AsyncLock = require('nlocks/async-lock');
|
|
|
|
const lock = new AsyncLock();
|
|
|
|
async function protectedOperation() {
|
|
await lock.acquire();
|
|
try {
|
|
// Your critical section code here
|
|
console.log('Performing protected operation');
|
|
await someAsyncWork();
|
|
} finally {
|
|
lock.release();
|
|
}
|
|
}
|
|
```
|
|
|
|
### FileLock
|
|
|
|
A file-based lock for synchronizing operations across multiple Node.js processes:
|
|
|
|
```javascript
|
|
const FileLock = require('nlocks/file-lock');
|
|
|
|
const lock = new FileLock();
|
|
|
|
async function fileProtectedOperation() {
|
|
await lock.acquire('/path/to/your/file.txt');
|
|
try {
|
|
// Your file operation code here
|
|
console.log('Performing file operation');
|
|
await someFileAsyncWork();
|
|
} finally {
|
|
lock.release('/path/to/your/file.txt');
|
|
}
|
|
}
|
|
```
|
|
|
|
## API
|
|
|
|
### AsyncLock
|
|
|
|
- `new AsyncLock()` - Creates a new AsyncLock instance
|
|
- `acquire(): Promise<void>` - Acquires the lock
|
|
- `release(): void` - Releases the lock
|
|
|
|
### FileLock
|
|
|
|
- `new FileLock()` - Creates a new FileLock instance
|
|
- `acquire(filePath): Promise<void>` - Acquires a lock for the specified file path
|
|
- `release(filePath): void` - Releases the lock for the specified file path
|
|
|
|
## Testing
|
|
|
|
Run the test suite with:
|
|
|
|
```bash
|
|
npm test
|
|
```
|
|
|
|
## License
|
|
|
|
[MIT](LICENSE) |