Introduction to Lockfile
The lockfile module provides a simple way to manage file-based locks in Node.js, ensuring that only one instance of your script or critical section of your code is executing at any time. This is especially useful in preventing race conditions in concurrent processes. In this guide, we will delve into various APIs provided by the lockfile module along with practical code snippets and a comprehensive app example to illustrate their usage.
Basic Usage
To begin using the lockfile module, you need to install it first:
npm install lockfile
Here is a simple example of creating a lockfile:
const lockfile = require('lockfile');
lockfile.lock('path/to/file.lock', function (er) {
if (er) {
console.error('Failed to acquire lock:', er);
return;
}
console.log('Lock acquired');
// Perform task
// Remember to unlock
lockfile.unlock('path/to/file.lock', function (er) {
if (er) {
console.error('Failed to release lock:', er);
} else {
console.log('Lock released');
}
});
});
Locking with Options
You can customize the lockfile behavior using options:
const opts = {
wait: 1000, // Wait for 1000 ms before retrying
pollPeriod: 100, // Check every 100 ms
stale: 60000, // Stale duration in ms
retries: 3, // Number of retries before giving up
retryWait: 100 // Wait 100 ms before retrying
};
lockfile.lock('path/to/anotherfile.lock', opts, function (er) {
if (er) {
console.error('Failed to acquire lock:', er);
return;
}
console.log('Lock acquired with options');
// Perform task
lockfile.unlock('path/to/anotherfile.lock', function (er) {
if (er) {
console.error('Failed to release lock:', er);
} else {
console.log('Lock released with options');
}
});
});
Check Lock Status
It’s important to check if a lockfile already exists:
lockfile.check('path/to/file.lock', function (er, isLocked) {
if (er) {
console.error('Failed to check lock status:', er);
return;
}
console.log('Is file locked?', isLocked);
});
App Example Using Lockfile
Let’s create a small application that simulates a task requiring a lock to avoid concurrency issues:
const express = require('express');
const lockfile = require('lockfile');
const fs = require('fs');
const app = express();
const PORT = 3000;
app.get('/process', (req, res) => {
const filePath = 'path/to/process.lock';
lockfile.lock(filePath, { retries: 10, retryWait: 200 }, function (er) {
if (er) {
res.status(503).send('Server busy, try again later.');
return;
}
console.log('Lock acquired for processing');
// Simulate processing
setTimeout(() => {
lockfile.unlock(filePath, function (er) {
if (er) {
res.status(500).send('Failed to release lock.');
console.error('Failed to release lock', er);
return;
}
console.log('Lock released after processing');
res.send('Processing complete');
});
}, 5000); // Simulate a 5-second task
});
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
In this application, the server processes requests at the /process
endpoint, ensuring that only one process can handle the request at a time by using the lockfile module. This helps prevent overlapping tasks and ensures data integrity.
By leveraging the lockfile module, you can easily manage concurrent processes and avoid potential issues related to race conditions in your Node.js applications.
Happy coding!
Hash: d6f5483103ee386e1f3453bff6da949b7d95fe942218d3774a449e38bbd9317f