javascript - Node.js return result of file -


i'd make node.js function that, when calls, reads file, , returns contents. i'm having difficulty doing because 'fs' evented. thus, function has this:

function render_this() {     fs.readfile('sourcefile', 'binary', function(e, content) {         if(e) throw e;         // have content here, how tell people?     });     return /* oh no can't access contents! */; }; 

i know there might way using non-evented io, i'd prefer answer allows me wait on evented functions i'm not stuck again if come situation need same thing, not io. know breaks "everything evented" idea, , don't plan on using often. however, need utility function renders haml template on fly or something.

finally, know can call fs.readfile , cache results on, won't work because in situation 'sourcefile' may change on fly.

ok, want make development version automatically load , re-render file each time changes, right?

you can use fs.watchfile monitor file , re-render template each time changed, suppose you've got kind of global variable in states whether server running in dev or production mode:

var fs = require('fs'); var http = require('http'); var dev_mode = true;  // let's encapsulate nasty bits! function cachedrenderer(file, render, refresh) {     var cacheddata = null;     function cache() {          fs.readfile(file, function(e, data) {             if (e) {                 throw e;             }             cacheddata = render(data);         });          // watch file if, needed , re-render + cache whenever changes          // may move cachedrenderer different file , use global config option instead of refresh parameter         if (refresh) {             fs.watchfile(file, {'persistent': true, 'interval': 100}, function() {                 cache();             });             refresh = false;         }     }      // simple getter     this.getdata = function() {         return cacheddata;     }      // initial cache     cache(); }   var ham = new cachedrenderer('foo.haml',      // supply custom render function here     function(data) {         return 'render' + data + 'render';     },     dev_mode );   // start server http.createserver(function(req, res) {     res.writehead(200);     res.end(ham.getdata());  }).listen(8000); 

create cachedrenderer , access it's getdata property whenever needed, in case you're in development mod automatically re-render file each time changes.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -