diff --git a/lib/datastore.js b/lib/datastore.js index 1b3a70d..cc21bd2 100755 --- a/lib/datastore.js +++ b/lib/datastore.js @@ -22,6 +22,9 @@ var customUtils = require('./customUtils') * @param {Function} options.afterSerialization/options.beforeDeserialization Optional, serialization hooks * @param {Number} options.corruptAlertThreshold Optional, threshold after which an alert is thrown if too much data is corrupt * @param {Function} options.compareStrings Optional, string comparison function that overrides default for sorting + * + * Event Emitter - Events + * * compaction.done - Fired whenever a compaction operation was finished */ function Datastore (options) { var filename; @@ -74,6 +77,8 @@ function Datastore (options) { }); } } +util.inherits(Datastore, require('events')); + /** * Load the database from the datafile, and trigger the execution of buffered commands if any diff --git a/lib/persistence.js b/lib/persistence.js index a83563a..88a4948 100755 --- a/lib/persistence.js +++ b/lib/persistence.js @@ -134,7 +134,11 @@ Persistence.prototype.persistCachedDatabase = function (cb) { } }); - storage.crashSafeWriteFile(this.filename, toPersist, callback); + storage.crashSafeWriteFile(this.filename, toPersist, function (err) { + if (err) { return callback(err); } + self.db.emit('compaction.done'); + return callback(null); + }); }; diff --git a/test/persistence.test.js b/test/persistence.test.js index e7d77ed..ab1869a 100755 --- a/test/persistence.test.js +++ b/test/persistence.test.js @@ -144,7 +144,7 @@ describe('Persistence', function () { treatedData.length.should.equal(2); _.isEqual(treatedData[0], { _id: "1", a: 2, ages: [1, 5, 12] }).should.equal(true); _.isEqual(treatedData[1], { _id: "3", today: now }).should.equal(true); - }); + }); it('Compact database on load', function (done) { d.insert({ a: 2 }, function () { @@ -299,6 +299,15 @@ describe('Persistence', function () { }); }); + it("Can listen to compaction events", function (done) { + d.on('compaction.done', function () { + d.removeAllListeners('compaction.done'); // Tidy up for next tests + done(); + }); + + d.persistence.compactDatafile(); + }); + describe('Serialization hooks', function () { var as = function (s) { return "before_" + s + "_after"; }