Skip to content

Instantly share code, notes, and snippets.

@danmactough
Created September 28, 2016 01:42
Show Gist options
  • Save danmactough/3b63f5e16d172911204c4a65074ce65b to your computer and use it in GitHub Desktop.
Save danmactough/3b63f5e16d172911204c4a65074ce65b to your computer and use it in GitHub Desktop.
var fs = require("fs");
var path = require("path");
var outfile = path.resolve(__dirname, "appPrefs.json");
var lockfile = outfile + ".lock";
var data = "some data or other";
// obtain an exclusive read/write file handle on the semaphore file
fs.open(lockfile, "wx+", function (err, fd) {
if (err) {
console.warn("Failed to obtain exclusive lock");
}
else {
// if we obtained the lock, we may write to the output file
fs.writeFile(outfile, data, function (err) {
if (err) {
console.error(err.stack);
}
// close the file handle so we don't leak resources
fs.close(fd, function (err) {
if (err) {
console.error(err.stack);
}
// remove the semaphore file
fs.unlink(lockfile, function (err) {
if (err) {
console.error(err.stack);
process.exit(1);
}
process.exit();
});
});
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment