Skip to content

Instantly share code, notes, and snippets.

@martintajur
Created January 19, 2012 14:36
Show Gist options
  • Save martintajur/1640341 to your computer and use it in GitHub Desktop.
Save martintajur/1640341 to your computer and use it in GitHub Desktop.
Simple lock-file mechanism for nodeJS
var fs = require('fs');
var path = require('path');
if (typeof exports === 'undefined') var exports = {};
exports.exists = function(filename) {
try {
return (fs.lstatSync(filename) ? true : false);
}
catch (err) {
return false;
}
};
exports.create = function(filename, contents) {
try {
if (!contents) contents = '';
fs.writeFileSync(filename, contents);
return true;
}
catch (err) {
return false;
}
};
exports.remove = function(filename) {
try {
return fs.unlinkSync(filename);
}
catch (err) {
return false;
}
};
@martintajur
Copy link
Author

@adminy This was done 9 years ago so a lot has happened since then. I'd have to be honest and admit this stuff is all outdated here :)

@adminy
Copy link

adminy commented Feb 5, 2021

@martintajur Code lives on ... provide a nice gist to others, something like:

const { promises, constants } = require('fs')
const lockFile = path => {
    const lockPath = `${path}.lock`
    return promises.open(lockPath, constants.O_CREAT | constants.O_EXCL | constants.O_RDWR).catch(() => lockFile(path))
}
const unlockFile = path => {
    const lockPath = `${path}.lock`
    return promises.unlink(lockPath).catch(() => unlockFile(path)
}

Usage:

const main = async () => {
    const path = 'some/path/to/file'
    await lockFile(path)
    // Do something with the file
    // ...
    await unlockFile(path)
}
main()

Proper locking mechanisms are probably more intricate than that, taking in consideration oses and their filesystems but It is nice to have a simple example to find somewhere.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment