From c05d039851bed60cf300f8284c2cb3905d15b52c Mon Sep 17 00:00:00 2001 From: wblankenship Date: Fri, 22 Jul 2016 15:13:54 -0400 Subject: [PATCH] Writes config to temp file then renames to dest This protects against corrupting the configuration file if the application crashes before the stream finishes writing to the file Especially important for large configuration files --- index.js | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index dd728a6..7f3fcf0 100644 --- a/index.js +++ b/index.js @@ -33,7 +33,15 @@ ApplicationConfig.prototype.write = function (data, cb) { mkdirp(directoryPath, function (err) { if (err) { return cb(err) } - fs.writeFile(self.filePath, JSON.stringify(data, null, 2), cb) + var tempFilePath = + self.filePath + + Math.random().toString().substr(2) + + Date.now().toString() + fs.writeFile(tempFilePath, JSON.stringify(data, null, 2), function (err) { + if (err) { return cb(err) } + + fs.rename(tempFilePath, self.filePath, cb) + }) }) }