Created
September 5, 2019 15:50
-
-
Save scripting/6ca719a6c332be44e6ff6c82517a34ba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "proxypersisttest", | |
"description": "A little test app that uses JavaScript proxy to manage a persistent stats object.", | |
"author": "Dave Winer <[email protected]>", | |
"license": "MIT", | |
"version": "0.4.0", | |
"dependencies" : { | |
"daveutils": "*" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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