-
Notifications
You must be signed in to change notification settings - Fork 110
Hot reload
Node.js code hot reload can bring a lot of benifits, for example, you can hot update code in production, fix an emergency bug, change the logic of code. Especially when in a long connection service, restarting server will make users logout and then reconnect, it is not bad for user experiences. However, by default, hot code reload is not supported in Node.js, because when doing hot reload, it is necessary to keep the reference of the objects, which may cause memory leak.
Bearcat provides a way for hot reload code, of course, there are some limits, not all codes updated will be hot reloaded.
Bearcat hot reload is based on Bearcat powerful IoC container, to watch some events, when hot reload files changed, Bearcat will dynamically replace the updated POJO's prototype functions. Therefore, because objects are shared with the same prototype object, when dynamically update the prototype object, all objects will be hot updated, without any influence to the objects' private fields.
That is to say that what bearcat hot reload is actually the prototype functions, when you want to update a private field, it is not supported.
Bearcat will watch your application runtime directory's sub-directory hot, when it'is updated, bearcat will do hot reload for the updated files
hot/car.js
var Car = function() {
}
Car.prototype.run = function() {
console.log('run hot car...');
return 'car hot';
}
module.exports = {
id: "car",
func: Car
}
Because bearcat updates the prototype, the updated files need to provide the updated bean's id and func, to imply which bean need to be updated and the newest prototype function definitions.
If you use $ annoatation to declare the meta configurations, there is no need to exports an id and func, hot codes is the same as what you use $ annoatation declares
bus.js
var Bus = function() {
this.$id = "bus";
}
Bus.prototype.run = function() {
return 'bus';
}
module.exports = Bus;
hot/bus.js
var Bus = function() {
this.$id = "bus";
}
Bus.prototype.run = function() {
return 'bus hot';
}
module.exports = Bus;
Note:
- To change the default watch directory, you can start your app with hpath arguments to specify the hot reload watch directory
node app hpath=xxx
or
node app --hpath=xxx
-
Current verision of bearcat uses fs.watch to implement watching directory, therefore, it only watch the first level of directory, when you add a sub-directory to the hot directory, hot reload will be failed, it is not supported now
-
Avoid using gloal var in file, require by relative path when doing hot reload, because all of these are tightly coupled
- Loosely coupled system makes it easy to hot reload part of codes, Bearcat uses IoC to decouple the dependency of objects
enable process.env.BEARCAT_HOT = 'off'; to shutoff bearcat hot reload code function, will not watch hot reload path