如何根据请求编译jade而不仅仅是服务器启动?
问题描述:
我正在寻找在服务器请求/响应上编译我的翡翠,这样我可以对玉文件进行更改并实时查看,而不必每次都重新启动服务器。这是迄今为止的假模型。如何根据请求编译jade而不仅仅是服务器启动?
var http = require('http')
, jade = require('jade')
, path = __dirname + '/index.jade'
, str = require('fs').readFileSync(path, 'utf8');
function onRequest(req, res) {
req({
var fn = jade.compile(str, { filename: path, pretty: true});
});
res.writeHead(200, {
"Content-Type": "text/html"
});
res.write(fn());
res.end();
}
http.createServer(onRequest).listen(4000);
console.log('Server started.');
我希望我明白了!
答
您只在服务器启动时读取一次文件。如果你想拥有它读取的变化,你不得不看它的要求,这意味着你的实体模型看起来更象:
function onRequest(req, res) {
res.writeHead(200, {
"Content-Type": "text/html"
});
fs.readFile(path, 'utf8', function (err, str) {
var fn = jade.compile(str, { filename: path, pretty: true});
res.write(fn());
res.end();
});
}
类似的东西会每次读取的文件,这是可能是好的开发的目的,但如果你只有想更改/处理文件,你可能会使用文件观察器(fs.watch
可能适合此法案)。
像这样(只是一个未经测试的例子作为一个想法):
var fn;
// Clear the fn when the file is changed
// (I don't have much experience with `watch`, so you might want to
// respond differently depending on the event triggered)
fs.watch(path, function (event) {
fn = null;
});
function onRequest(req, res) {
res.writeHead(200, {
"Content-Type": "text/html"
});
var end = function (tmpl) {
res.write(tmpl());
res.end();
};
if (fn) return end(fn);
fs.readFile(path, 'utf8', function (err, str) {
fn = jade.compile(str, { filename: path, pretty: true});
end(fn);
});
}
什么exactely是问题吗?你的方法看起来很有前途...... –
最初我有'var fn = jade.compile(str,{filename:path,pretty:true});'在顶部,但只有在服务器启动时才运行一次。因此,如果我要对我的玉石模板进行更改,我必须手动停止并启动服务器才能看到真正烦人的更改。我希望它在每次请求服务器时都创建该变量 – Datsik