From 11a1981dee4a586e6d892468aef7c698a14dad76 Mon Sep 17 00:00:00 2001 From: David Glasser Date: Wed, 5 Mar 2014 14:32:49 -0800 Subject: [PATCH] Write data file atomically --- tools/files.js | 8 ++++++++ tools/package-client.js | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/tools/files.js b/tools/files.js index d6c7b5a1b2..1cece4d4bb 100644 --- a/tools/files.js +++ b/tools/files.js @@ -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 diff --git a/tools/package-client.js b/tools/package-client.js index 2907d4ab67..b816059bf1 100644 --- a/tools/package-client.js +++ b/tools/package-client.js @@ -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() {