[英]How to update server's content without restarting it? (node.js)
所以我有一个简单的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);
现在,假设我想更新我的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
);
}
和
// app.js
var app = require('express')();
app.get('/message/:poster', require('./lib.js').message)
app.listen(2345);
它工作,但如果我更新lib.js它不会更新。 它似乎正在制作该功能的副本。
然后我试了一下
// app.js
var app = require('express')();
app.get('/message/:poster', function(request, response) {
require('./lib.js').message(request, response);
})
app.listen(2345);
但这也不会更新。
似乎函数一直被缓存和重用(一旦我启动服务器)。 我敢说必须有一种方法来设置它,以便它每次重新验证函数(检查包含它的文件是否更改),如果是这样更新其缓存,或者我们可以将其设置为每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 。
如果您不想在生产中丢失任何请求 - 只需使用PM2,Forever等优雅重启您的应用程序。如果您想在开发中自动应用您的更改 - 请使用Nodemon。 我不知道为什么你不想重新启动应用程序的任何其他原因。
将内容导出到其他模块似乎是解决此要求的好方法。 但问题是:模块只被实例化一次并缓存以供以后的请求使用,这就是为什么在更新lib.js时它不会反映更新的内容。
你在寻找什么是一种热加载node.js模块的方法,以便在每次更改时获得模块的新实例。 您可以使用node-hotswap
require('hotswap');
对于您要跟踪更改的任何模块:
module.change_code = 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.