I’d like to make a node.js function that, when calls, reads a file, and returns the contents. I’m having difficulty doing this because ‘fs’ is evented. Thus, my function has to look like this:
function render_this() {
fs.readFile('sourcefile', 'binary', function(e, content) {
if(e) throw e;
// I have the content here, but how do I tell people?
});
return /* oh no I can't access the contents! */;
};
I know that there might be a way to do this using non-evented IO, but I’d prefer an answer that allows me to wait on evented functions so that I’m not stuck again if I come to a situation where I need to do the same thing, but not with IO. I know that this breaks the “everything is evented” idea, and I don’t plan on using it very often. However, sometimes I need a utility function that renders a haml template on the fly or something.
Finally, I know that I can call fs.readFile and cache the results early on, but that won’t work because in this situation ‘sourcefile’ may change on the fly.
OK, so you want to make your development version to automatically load and re-render the file each time it changes, right?
You can use
fs.watchFileto monitor the file and then re-render the template each time it changed, I suppose you’ve got some kind of global variable in your which states whether the server is running in dev or production mode:Create a
cachedRendererand then access it’sgetDataproperty whenever needed, in case you’re in development mod it will automatically re-render the file each time it changes.