Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
{
"name": "proxypersisttest",
"description": "A little test app that uses JavaScript proxy to manage a persistent stats object.",
"author": "Dave Winer <dave@scripting.com>",
"license": "MIT",
"version": "0.4.0",
"dependencies" : {
"daveutils": "*"
}
}
const utils = require ("daveutils");
const fs = require ("fs");
function makePersistentProxy (nameobject, obj, callback) {
var fname = nameobject + ".json";
var flchanged = false;
var theTarget;
function saveIfChanged () {
if (flchanged) {
flchanged = false;
fs.writeFile (fname, utils.jsonStringify (theTarget), function (err) {
});
}
}
function get (target, name) {
return (target [name]);
}
function set (target, name, value) {
console.log ("name == " + name + ", value == " + value);
target [name] = value;
flchanged = true;
theTarget = target;
}
fs.readFile (fname, function (err, data) {
if (!err) {
try {
var jstruct = JSON.parse (data);
for (var x in jstruct) {
obj [x] = jstruct [x];
}
}
catch (err) {
console.log (err.message);
}
}
setInterval (saveIfChanged, 1000);
callback (new Proxy (obj, {get, set}));
});
}
var initialstats = {
ct: 0,
slogan: "",
randomNumber: 0
}
var stats;
function everySecond () {
stats.ct++;
stats.slogan = utils.getRandomSnarkySlogan ();
stats.randomNumber = utils.random (0, 10000);
}
makePersistentProxy ("stats", initialstats, function (theProxy) {
stats = theProxy;
setInterval (everySecond, 1000);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.