Skip to content

Instantly share code, notes, and snippets.

@danmactough danmactough/write.js
Created Sep 28, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.