Write data file atomically

This commit is contained in:
David Glasser
2014-03-05 14:32:49 -08:00
parent 984b1d4096
commit 11a1981dee
2 changed files with 9 additions and 1 deletions

View File

@@ -482,6 +482,14 @@ files.renameDirAlmostAtomically = function (fromDir, toDir) {
files.rm_recursive(garbageDir);
};
files.writeFileAtomically = function (filename, contents) {
var tmpFile = path.join(
path.dirname(filename),
'.' + path.basename(filename) + '.' + utils.randomToken());
fs.writeFileSync(tmpFile, contents);
fs.renameSync(tmpFile, filename);
};
// Run a program synchronously and, assuming it returns success (0),
// return whatever it wrote to stdout, as a string. Otherwise (if it
// did not exit gracefully and return 0) return null. As node has

View File

@@ -85,7 +85,7 @@ var writePackagesToDisk = function (syncToken, collectionData) {
var filename = config.getPackageStorage();
// XXX think about permissions?
files.mkdir_p(path.dirname(filename));
fs.writeFileSync(filename, JSON.stringify(finalWrite, null, 2));
files.writeFileAtomically(filename, JSON.stringify(finalWrite, null, 2));
};
loadPackageData = function() {