Cor*_*ped 5 javascript node.js express
所以我有一个简单的node.js服务器,它只提供动态内容:
// app.js
var app = require('express')();
app.get('/message/:poster', function(request, response) {
response.writeHeader(200, {'content-type': 'text/html'});
// some database queries
response.end(""+
"<!DOCTYPE html>"+
"<html>"+
"<head>"+
"<title>messages of "+request.params.poster+"</title>"+
"<script src='http://example.com/script.js'></script>"+
"<link rel='stylesheet' href='http://example.com/style.css'>"+
"</head>"+
"<body>"+
"" // and so on
);
})
app.listen(2345);
Run Code Online (Sandbox Code Playgroud)
现在,假设我想更新我的HTML.
并且进一步假设我不想重新启动服务器.
有没有办法实现这个目标?
我尝试导出部件以发送到外部文件,如:
// lib.js
module.exports.message = function(request, response) {
response.writeHeader(200, {'content-type': 'text/html'})
//some database queries
response.end(""+
"<!DOCTYPE html>"+
"<html>"+
"<head>"+
"<title>messages of "+request.params.poster+"</title>"+
"<script src='http://example.com/script.js></script>"+
"<link rel='stylesheet' href='http://example.com/style.css'>"+
"</head>"+
"<body>"+
"" //and so on
);
}
Run Code Online (Sandbox Code Playgroud)
和
// app.js
var app = require('express')();
app.get('/message/:poster', require('./lib.js').message)
app.listen(2345);
Run Code Online (Sandbox Code Playgroud)
它工作,但如果我更新lib.js它不会更新.它似乎正在制作该功能的副本.
然后我试了一下
// app.js
var app = require('express')();
app.get('/message/:poster', function(request, response) {
require('./lib.js').message(request, response);
})
app.listen(2345);
Run Code Online (Sandbox Code Playgroud)
但这也不会更新.
似乎函数一直被缓存和重用(一旦我启动服务器).我敢说必须有一种方法来设置它,以便它每次重新验证函数(检查包含它的文件是否更改),如果是这样更新其缓存,或者我们可以将其设置为每n次更新函数时间,甚至更好,因为我们在节点中,有一个事件监听器来更改包含该函数的文件,并且随着函数的更改,事件触发和缓存中的函数得到更新.
那么我们如何得到上述行为之一呢?或者是其他东西?我知道重新启动服务器可能只需要100毫秒,但重新启动它会中断所有当前活动的websockets,这不是一个选项.
注意:我不想使用任何模板语言,如jade,ejc等.
通过要求一个模块,它module.exports被缓存以用于将来的所有调用require.您可以通过编程方式清空缓存:http://nodejs.org/docs/latest/api/globals.html#globals_require_cache.如果您还想在文件更改时执行此操作,可以使用fs.watch:http://nodejs.org/api/fs.html#fs_fs_watch_filename_options_listener.