varstructr=require("structr"),fs=require("fs");varConfig=structr({/** */"__construct": function(file){this.configFile=file;},/** * loads the config file */"load": function(next){varself=this;//make sure the confg file existsfs.stat(this.configFile,function(err,stat){//if it doesn't exist, then set the config to an object, and//skip the restif(err){self._config={};returnnext();}//otherwise load itfs.readFile(self.configFile,function(err,content){//and set the confignext(null,self._config=JSON.parse(content));})});},/** * returns the value in a config. This is blocked until * the config has been loaded */"getValue": function(key,next){returnthis._config[key];},/** * sets the vaue in the config */"setValue": function(key,value,next){this._config[key]=value;this.save();next();},/** * saves the config */"step save": function(next){fs.writeFile(this.configFile,JSON.stringify(this._config),next);}});varconfig=newConfig(__dirname+"/cache.json");config.load(function(err){if(err)return;varvalue=config.getValue("name");//do stuff...});
Into This
varstructr=require("structr"),fs=require("fs");//mix into structrstructr.mixin(require("../"));varConfig=structr({/** */"__construct": function(file){this.configFile=file;//load the config before any methods can be//calledthis.load();},/** * loads the config file */"step load": function(nextFn){this.step(//make sure the confg file existsfunction(next){fs.stat(this.configFile,next);},//if it doesn't exist, then set the config to an object, and//skip the rest. Otherwise load it.function(err,stats,next){if(err){this._config={};returnnextFn(err);}fs.readFile(this.configFile,next);},//set the config, and finishfunction(err,content,next){next(null,this._config=JSON.parse(content));},//continue onto any other function called in this confignextFn);},/** * returns the value in a config. This is blocked until * the config has been loaded */"step getValue": function(key,next){next(null,this._config[key]);},/** * sets the vaue in the config */"step setValue": function(key,value,next){this._config[key]=value;this.save();next();},/** * saves the config */"step save": function(next){fs.writeFile(this.configFile,JSON.stringify(this._config),next);}});varconfig=newConfig(__dirname+"/cache.json");config.getValue("name",function(err,value){if(!value){console.log("config value does not exist, saving!");config.setValue("name","craig");}else{console.log("hello %s!",value);}});