关于我如何在Node.js中实现文件的自动重载有什么想法吗?我厌倦了每次更改文件时重新启动服务器。 显然,Node.js的require()函数不会重新加载文件,如果他们已经被要求,所以我需要做这样的事情:

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全局变量的线索。


当前回答

长期以来,Nodemon一直是重新启动服务器进行文件更改的首选。现在在Node.js 19中,他们引入了一个——watch标志,它做同样的[实验]。文档

node --watch index.js

其他回答

不需要使用恶魔或其他类似的工具。只需使用IDE的功能。

可能最好的一个是IntelliJ WebStorm,具有热重载功能(自动服务器和浏览器重载)的node.js。

如果有人仍然遇到这个问题,并希望仅使用标准模块来解决它,我做了一个简单的例子:

var process = require('process');
var cp = require('child_process');
var fs = require('fs');

var server = cp.fork('server.js');
console.log('Server started');

fs.watchFile('server.js', function (event, filename) {
    server.kill();
    console.log('Server stopped');
    server = cp.fork('server.js');
    console.log('Server started');
});

process.on('SIGINT', function () {
    server.kill();
    fs.unwatchFile('server.js');
    process.exit();
});

这个例子只针对一个文件(server.js),但是可以使用一个文件数组,一个for循环来获取所有文件名,或者通过监视目录来适应多个文件:

fs.watch('./', function (event, filename) { // sub directory changes are not seen
    console.log(`restart server`);
    server.kill();
    server = cp.fork('server.js');    
})

这段代码是为Node.js 0.8 API制作的,它不适合一些特定的需求,但可以在一些简单的应用程序中工作。

更新: 这个函数是在我的模块simple, GitHub repo中实现的

长期以来,Nodemon一直是重新启动服务器进行文件更改的首选。现在在Node.js 19中,他们引入了一个——watch标志,它做同样的[实验]。文档

node --watch index.js

节点管理器很棒

在保存旧版本的节点时重新启动(不建议):

npm install supervisor -g
supervisor app.js

对于带有npx的Node版本,使用在保存时重新启动:

npm install supervisor
npx supervisor app.js

或者直接在NPM脚本中调用supervisor:

"scripts": {
  "start": "supervisor app.js"
}

我找到了一个简单的方法:

delete require.cache['/home/shimin/test2.js']