From 9867a7a6020e64c8a2bea60f6dc0cf2b48771c3e Mon Sep 17 00:00:00 2001 From: Kevin Martensson Date: Tue, 4 Aug 2015 16:13:42 +0200 Subject: [PATCH] Use `write-file-atomic` to avoid corruption Fixes #20. --- index.js | 5 +++-- package.json | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index cffeb1b..0791cbe 100644 --- a/index.js +++ b/index.js @@ -7,6 +7,7 @@ var mkdirp = require('mkdirp'); var uuid = require('uuid'); var xdgBasedir = require('xdg-basedir'); var osTmpdir = require('os-tmpdir'); +var writeFileAtomic = require('write-file-atomic'); var user = (osenv.user() || uuid.v4()).replace(/\\/g, ''); var configDir = xdgBasedir.config || path.join(osTmpdir(), user, '.config'); @@ -38,7 +39,7 @@ Configstore.prototype = Object.create(Object.prototype, { // empty the file if it encounters invalid JSON if (err.name === 'SyntaxError') { - fs.writeFileSync(this.path, '', writeFileOptions); + writeFileAtomic.sync(this.path, '', writeFileOptions); return {}; } @@ -51,7 +52,7 @@ Configstore.prototype = Object.create(Object.prototype, { // could have been deleted in the meantime mkdirp.sync(path.dirname(this.path), defaultPathMode); - fs.writeFileSync(this.path, JSON.stringify(val, null, '\t'), writeFileOptions); + writeFileAtomic.sync(this.path, JSON.stringify(val, null, '\t'), writeFileOptions); } catch (err) { // improve the message of permission errors if (err.code === 'EACCES') { diff --git a/package.json b/package.json index e54c774..20d79bf 100644 --- a/package.json +++ b/package.json @@ -35,6 +35,7 @@ "os-tmpdir": "^1.0.0", "osenv": "^0.1.0", "uuid": "^2.0.1", + "write-file-atomic": "^1.1.2", "xdg-basedir": "^2.0.0" }, "devDependencies": {