Created
January 19, 2012 14:36
-
-
Save martintajur/1640341 to your computer and use it in GitHub Desktop.
Simple lock-file mechanism for nodeJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 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
@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 :)