如何在Node.js中自动重新加载文件?

衡泰
2023-12-01

本文翻译自:How to auto-reload files in Node.js?

Any ideas on how I could implement an auto-reload of files in Node.js? 关于如何在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: 显然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 );

And in the app.js file I have: app.js文件中我有:

var file = require('./file');
this.app = function(req, res) { 
    file.serveFile( req, res, 'file.js');  
}

But this also isn't working - I get an error in the process.compile() statement saying that 'require' is not defined. 但是这也没有用 - 我在process.compile()语句中得到一个错误,说没有定义'require'。 process.compile is evaling the app.js , but has no clue about the node.js globals. process.compile正在评估app.js ,但对node.js全局变量没有任何线索。


#1楼

参考:https://stackoom.com/question/8H4M/如何在Node-js中自动重新加载文件


#2楼

If somebody still comes to this question and wants to solve it using only the standard modules I made a simple example: 如果有人仍然只是使用标准模块来解决这个问题我做了一个简单的例子:

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();
});

This example is only for one file (server.js), but can be adapted to multiple files using an array of files, a for loop to get all file names, or by watching a directory: 此示例仅适用于一个文件(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');    
})

This code was made for Node.js 0.8 API, it is not adapted for some specific needs but will work in some simple apps. 这段代码是针对Node.js 0.8 API编写的,它不适合某些特定需求,但可以在一些简单的应用程序中使用。

UPDATE: This functional is implemented in my module simpleR , GitHub repo 更新:此功能在我的模块simpleRGitHub repo中实现


#3楼

A good, up to date alternative to supervisor is nodemon : 对于supervisor来说,一个好的,最新的替代方案是nodemon

Monitor for any changes in your node.js application and automatically restart the server - perfect for development 监视node.js应用程序中的任何更改并自动重新启动服务器 - 非常适合开发

To use nodemon : 要使用nodemon

$ npm install nodemon -g
$ nodemon app.js

#4楼

Edit: My answer is obsolete. 编辑:我的答案已经过时了。 Node.js is a very fast changing technology. Node.js是一种快速变化的技术。

I also wondered about reloading modules. 我也想知道重装模块。 I modified node.js and have published the source at Github at nalply/node . 我修改了node.js,并在nalply / node的 Github上发布了源代码。 The only difference is the function require . 唯一的区别是功能require It has an optional second argument reload . 它有一个可选的第二个参数reload

require(url, reload)

To reload app.js in current directory use 要在当前目录中重新加载app.js ,请使用

app = require("./app", true);

Write something like this, and you have auto -reload: 写这样的东西,你有自动重载:

process.watchFile(script_name, function(curr, prev) {
    module = reload(script_name, true);
});

The only problem I see is the variable module , but I am working at it now. 我看到的唯一问题是变量module ,但我现在正在努力。


#5楼

There was a recent thread about this subject on the node.js mailing list. 在node.js邮件列表上有一个关于这个主题的最新帖子 The short answer is no, it's currently not possible auto-reload required files, but several people have developed patches that add this feature. 简短的回答是否定的,目前不可能自动重新加载所需的文件,但有几个人开发了添加此功能的补丁。


#6楼

Use this: 用这个:

function reload_config(file) {
  if (!(this instanceof reload_config))
    return new reload_config(file);
  var self = this;

  self.path = path.resolve(file);

  fs.watchFile(file, function(curr, prev) {
    delete require.cache[self.path];
    _.extend(self, require(file));
  });

  _.extend(self, require(file));
}

All you have to do now is: 你现在要做的就是:

var config = reload_config("./config");

And config will automatically get reloaded :) 并且config会自动重新加载:)

 类似资料: