我有以下模块:
// vote.js
var db = require(./dirty-wrapper);
module.exports = function vote() {
var obj = {};
// increase the score
obj.inc = function(key) {
var pval = db.get(key);
if (!pval) pval = 0;
db.set(key, pval + 1);
};
// decrease the score
obj.dec = function(key) {
var pval = db.get(key);
if (!pval) pval = 0;
db.set(key, pval - 1);
};
// reset the score to 0
obj.reset = function(key) {
db.set(key, 0);
};
obj.get = function(key) {
return db.get(key);
};
return obj;
};
它使用这个简单的包装器来处理脏:
// dirty-wrapper.js
var dirty = require('dirty');
var db = dirty('vote.db');
module.exports = db.on('load', function() {
var obj = {};
obj.set = function(key, val, callback) {
db.set(key, val);
return callback();
};
obj.get = function(key, callback) {
return callback(db.get(key));
};
obj.reset = function(callback) {
db.forEach(function(key, val) {
val = 0;
});
return callback();
};
return obj;
});
这是我的简单客户:
// client.js
var vote = require('./vote.js')();
vote.inc('michael');
vote.inc('michael');
vote.inc('michael');
vote.inc('michael');
console.log('michael: ' + vote.get('michael')); // output = michael: 4
问题是当运行停止并且我再次启动客户端时,输出又是michael: 4
第二次运行后,vote.db
包含以下内容:
$ cat vote.db
{"key":"michael","val":1}
{"key":"michael","val":4}
{"key":"michael","val":4}
{"key":"michael","val":4}
{"key":"michael","val":1}
{"key":"michael","val":4}
{"key":"michael","val":4}
{"key":"michael","val":4}
append-only
首先,如果有人能解释该策略,那就太好了。其次,我想了解为什么 node-dirty 不会持续存在,即使它每次运行都会写入磁盘。
谢谢 ;)