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

查看:46
本文介绍了如何在 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');  
}

但这也不起作用 - 我在 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.

推荐答案

supervisor 的一个很好的、最新的替代方案是 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

在没有 npx 的 Node 版本中使用 nodemon(不建议使用 v8.1 及以下版本):

To use nodemon with version of Node without npx (v8.1 and below, not advised):

$ npm install nodemon -g
$ nodemon app.js

或者将 nodemonnpx 捆绑在 (v8.2+) 中的 Node 版本一起使用:

Or to use nodemon with versions of Node with npx bundled in (v8.2+):

$ npm install nodemon
$ npx nodemon app.js

或者作为 devDependency 在 package.json 中使用 npm 脚本:

Or as devDependency in with an npm script in package.json:

"scripts": {
  "start": "nodemon app.js"
},
"devDependencies": {
  "nodemon": "..."
}

这篇关于如何在 Node.js 中自动重新加载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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