diff --git a/lib/persistence.js b/lib/persistence.js index 8e006e8..888347a 100644 --- a/lib/persistence.js +++ b/lib/persistence.js @@ -23,6 +23,14 @@ function Persistence (options) { this.db = options.db; this.inMemoryOnly = this.db.inMemoryOnly; this.filename = this.db.filename; + + if (!this.inMemoryOnly && this.filename) { + if (this.filename.charAt(this.filename.length - 1) === '~') { + throw "The datafile name can't end with a ~, which is reserved for automatic backup files"; + } else { + this.tempFilename = this.filename + '~'; + } + } // For NW apps, store data in the same directory where NW stores application data if (this.filename && options.nodeWebkitAppName) { @@ -86,6 +94,8 @@ Persistence.prototype.persistCachedDatabase = function (cb) { var callback = cb || function () {} , toPersist = '' ; + + if (this.inMemoryOnly) { return callback(null); } this.db.getAllData().forEach(function (doc) { toPersist += model.serialize(doc) + '\n'; diff --git a/test/persistence.test.js b/test/persistence.test.js index 8fd5a94..7f474e1 100644 --- a/test/persistence.test.js +++ b/test/persistence.test.js @@ -252,10 +252,17 @@ describe('Persistence', function () { // This test is a bit complicated since it depends on the time actions take to execute - // It may not work as expected on all machines - // But it will not be seen as a failed test. The worst is that the timing is off and it would have worked on your machine regardless of the load failsafe - // It is timed for my dev machine + // It may not work as expected on all machines as it is timed for my machine + // That's why it is skipped, but all versions of nedb pass this test describe.only('Prevent dataloss when persisting data', function () { + + it('Creating a datastore with in memory as true and a bad filename wont cause an error', function () { + new Datastore({ filename: 'workspace/bad.db~', inMemoryOnly: true }); + }) + + it('Creating a persistent datastore with a bad filename will cause an error', function () { + (function () { new Datastore({ filename: 'workspace/bad.db~' }); }).should.throw(); + }) it('If system crashes during a loadDatabase, the former version is not lost', function (done) { var cp, N = 150000, toWrite = "", i;