如何在Node.js中自动重新加载文件? [英] How to auto-reload files in Node.js?

查看:173
本文介绍了如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆