Node.js返回文件的结果

我想做一个node.js函数,当调用,读取文件,并返回的内容。 我很难做到这一点,因为“FS”是平坦的。 因此,我的function看起来像这样:

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! */; }; 

我知道可能有办法做到这一点,使用non-even的IO,但我更喜欢一个答案,让我等待evented函数,以便我不会再卡住,如果我来到一个情况,我需要做同样的事情,但不与IO。 我知道这打破了“一切都是平的”的想法,我不打算经常使用它。 但是,有时候我需要一个实用的函数,它可以在飞行中或者其他的东西上呈现haml模板。

最后,我知道我可以调用fs.readFile并在早期caching结果,但是这样做不起作用,因为在这种情况下,sourcefile可能会随时改变。

好的,所以你想让你的开发版本自动加载并重新渲染文件,每次更改,对吧?

您可以使用fs.watchFile来监视文件,然后在每次更改模板时重新呈现模板,我想您已经在您的某个全局variables中指出了服务器是以开发还是生产模式运行:

 var fs = require('fs'); var http = require('http'); var DEV_MODE = true; // Let's encapsulate all the 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 the file if, needed and re-render + cache it whenever it changes // you may also move cachedRenderer into a different file and then use a global config option instead of the 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 your 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); 

创build一个cachedRenderer ,然后在需要的时候访问它的getData属性,以防你处于开发模式,每当它发生变化时它将自动重新呈现文件。

 function render_this( cb ) { fs.readFile('sourcefile', 'binary', function(e, content) { if(e) throw e; cb( content ); }); }; render_this(function( content ) { // tell people here });