Skip to content

Instantly share code, notes, and snippets.

@radiospiel
Created June 17, 2011 12:24
Show Gist options
  • Save radiospiel/1031330 to your computer and use it in GitHub Desktop.
Save radiospiel/1031330 to your computer and use it in GitHub Desktop.
/*
* Save this file as "kvs.js".
*
* Usage:
*
* node kvs.js set foo bar
*
* ... sets the "foo" entry to bar, and overwrites the kvs.js script with the updated data.
*
* node kvs.js set foo bar
*
* ... sets the "foo" entry to bar, and overwrites the kvs.js script with the updated data.
*
*/
App = {
//
// This must be this file's name, unless we are testing: the file in _filename
// will be overwritten by this file's operation.
_filename: "kvs.js",
//
// Run the command, as passed in from the command line, and
// dump the entire app into _filename.
_run: function() {
process.argv.shift();
var binary = process.argv.shift();
var cmd = process.argv.shift();
if(!cmd || cmd.substr(0,1) === "_" || App[cmd] === undefined) cmd = "usage";
if(!App[cmd].apply(this, process.argv)) return;
App._dump();
},
// Dump both App and Data into _filename
_dump: function() {
function dump(name, obj) {
var r = [];
for(var key in obj) {
if(obj.hasOwnProperty(key)) {
var v = obj[key];
v = typeof(v) === "function" ? "" + v : JSON.stringify(v);
r.push(' "' + key + '": ' + v);
}
}
var s = "/* ---- " + name + " ---- */\n" +
name + " = {\n" + r.join(",\n") + "\n};\n\n";
return s;
};
var js = dump("App", App) + dump("Data", Data) + "App._run();\n";
require("fs").writeFileSync(App._filename, js, "utf8");
},
// -- Application commands: must return true, if the application should be dumped.
usage: function() {
process.stderr.write("A simple key value store. Usage:\n\n");
process.stderr.write(" node " + App._filename + " set key value\n");
process.stderr.write(" node " + App._filename + " get key\n");
process.stderr.write(" node " + App._filename + " delete key\n");
process.stderr.write(" node " + App._filename + " list\n\n");
process.exit(1);
},
set: function(key, value) {
Data[key] = value;
return true;
},
"delete": function(key) {
delete Data[key];
return true;
},
get: function(key) {
if(!Data.hasOwnProperty(key))
process.exit(1);
process.stdout.write(Data[key] + "\n");
},
list: function(key) {
for(var key in Data) {
if(Data.hasOwnProperty(key))
process.stdout.write(key + "\n");
}
}
};
Data = {};
App._run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment