如何在Node.js中自动重新加载文件? [英] How to auto-reload files in Node.js?
问题描述
关于如何在Node.js中实现文件自动重载的任何想法?每次更改文件时,我都厌倦了重启服务器。
显然Node.js' require()
函数如果已经被要求就不会重新加载文件,所以我需要这样做:
Any ideas on how I could implement an auto-reload of files in Node.js? I'm tired of restarting the server every time I change a file.
Apparently Node.js' require()
function does not reload files if they already have been required, so I need to do something like this:
var sys = require('sys'),
http = require('http'),
posix = require('posix'),
json = require('./json');
var script_name = '/some/path/to/app.js';
this.app = require('./app').app;
process.watchFile(script_name, function(curr, prev){
posix.cat(script_name).addCallback(function(content){
process.compile( content, script_name );
});
});
http.createServer(this.app).listen( 8080 );
在 app.js 文件中我有:
var file = require('./file');
this.app = function(req, res) {
file.serveFile( req, res, 'file.js');
}
但这也无效 - 我在<$中收到错误c $ c> process.compile()声明说'require'未定义。 process.compile
正在评估 app.js ,但没有关于node.js全局变量的线索。
But this also isn't working - I get an error in the process.compile()
statement saying that 'require' is not defined. process.compile
is evaling the app.js, but has no clue about the node.js globals.
推荐答案
主管
的一个好的,最新的替代方案是 nodemon
:
A good, up to date alternative to supervisor
is nodemon
:
监控node.js应用程序中的任何更改并自动重启服务器 - 非常适合开发
Monitor for any changes in your node.js application and automatically restart the server - perfect for development
使用 nodemon
:
$ npm install nodemon -g
$ nodemon app.js
这篇关于如何在Node.js中自动重新加载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!