我有以下模塊:節點髒不從運行持續運行
// 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即使每次運行寫入磁盤都不會持續存在。
感謝;)
我想我在這裏混合了'sync'和'async'功能,它會導致一些問題,只是不確定這裏的經驗法則是什麼 – Michael