新增了基于命名管道的读写锁服务端和客户端实现,支持跨进程的读写锁同步机制。 主要功能包括: - 读写锁基本语义:允许多个读者并发访问,写者独占访问 - FIFO锁请求队列,确保公平性 - 客户端自动重连与超时机制 - 完整的单元测试覆盖各种锁竞争场景 - 支持 Windows 命名管道和 Unix Domain Socket 此功能可用于需要跨进程同步访问共享资源的场景,提供可靠的并发控制能力。 |
||
|---|---|---|
| __tests__ | ||
| .gitignore | ||
| LICENSE | ||
| README.md | ||
| async-lock.js | ||
| file-lock.js | ||
| index.js | ||
| jest.config.js | ||
| lock-client.namedpipe.js | ||
| lock.namedpipe.js | ||
| package.json | ||
README.md
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
npm install nlocks
Usage
Via index.js (recommended)
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:
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:
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 instanceacquire(): Promise<void>- Acquires the lockrelease(): void- Releases the lock
FileLock
new FileLock()- Creates a new FileLock instanceacquire(filePath): Promise<void>- Acquires a lock for the specified file pathrelease(filePath): void- Releases the lock for the specified file path
Testing
Run the test suite with:
npm test