autorestart 让nodejs代码即时生效

      写nodejs代码时,要使代码生效,就必须重启服务,虽然也不麻烦,但时间长了也会觉得烦,因此有一个工具能帮助我时代码即时生效是件很不错的事情,这里介绍一款工具:autorestart

      github地址:https://github.com/shimondoodkin/nodejs-autorestart

      比较可惜现在作者shimondoodkin   现在已经没怎么维护这个工程了,有部分内容在高版本的nodejs中已不能使用,但程序的大致架构还是在的,稍作修改即可使用。

     使用方法:

     下载代码之后,将nodejs.sh 和 autoexit.js 放到你项目工程代码的跟目录

     以最简单的代码为例,工程目录autoRestart,自己的代码文件是server.js,代码如下:

var http = require('http');

var app = http.createServer(function(req,res){
var str = 'hello world';
console.log(str);
res.writeHead(200,{});
res.end(str);
})
app.listen(9191,function(){
console.log('server is listening on 9191');
});

    再将nodejs.sh 和 autoexit.js放到autoRestart目录下,即:

     再在server中插入监控代码即可,最后server.js

//require.paths.unshift(__dirname); //make local paths accessible


var http = require('http');

var app = http.createServer(function(req,res){
var str = 'hello world';
console.log(str);
res.writeHead(200,{});
res.end(str);
})
app.listen(9191,function(){
console.log('server is listening on 9191');
});


// exit if any js file or template file is changed.
//
it is ok because this script encapsualated in a batch while(true);
//
so it runs again after it exits.
var autoexit_watch = require('./autoexit').watch;
//
var on_autoexit = function () { console.log('bye bye'); }
autoexit_watch(__dirname,".js", on_autoexit);
//autoexit_watch(__dirname+"/templates",".html", on_autoexit);

      特别说明,第一行被注释掉,是因为require.paths在nodejs的高版本中已经不被兼容。

  var autoexit_watch = require('./autoexit').watch 

     与项目源代码也稍有不同,请注意。

     最后,只要编辑nodejs.sh的脚本去使用你的server.js文件即可。

     启动程序:

./nodejs.sh

 

     讲好了使用方法,再简单讲诉要这个项目的原理。

     autoexit.js是监控目录下那些文件进行过改动,一旦文件发生过改动,程序要被关闭。

     而nodejs.sh则是不断尝试启动server.js(对,你没有听错,就是不断尝试启动),当autoexit.js使程序关闭退出后,nodejs.sh就真正返回作用使程序重启。

     两者相配合,就达到了使nodejs代码即时生效的作用。

 

    

posted @ 2012-01-09 23:01  lengyuhong  阅读(1693)  评论(0编辑  收藏  举报