我希望在服务器上编译我的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);
});
}