关于我如何在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全局变量的线索。


当前回答

用这个:

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

你现在要做的就是:

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

配置将自动被重新加载:)

其他回答

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

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中实现的

这里有一个在Windows中使用的低技术方法。把它放在一个名为server .bat的批处理文件中:

@echo off

:serve
start /wait node.exe %*
goto :serve

现在,不是从cmd shell运行node app.js,而是运行serve app.js。

这将打开一个运行服务器的新shell窗口。批处理文件将阻塞(因为/wait),直到您关闭shell窗口,此时原始的cmd shell将询问“终止批处理作业(Y/N)?”如果您回答“N”,则服务器将重新启动。

每次要重新启动服务器时,关闭服务器窗口并在cmd shell中回答“N”。

这是相当简单的,只是做这个自己没有任何依赖…内置的文件监视器已经足够成熟,它不像以前那么糟糕

你不需要任何复杂的子进程产卵/杀死和管道性病进出…你只需要一个简单的网络工作者,这就是全部!web Worker也是我在浏览器中使用的工具…所以坚持使用网络技术吧!Worker也将登录到控制台

import { watch } from 'node:fs/promises'
import { Worker } from 'node:worker_threads'

let worker = new Worker('./app.js')

async function reloadOnChange (dir) {
  const watcher = watch(dir, { recursive: true })
  for await (const change of watcher) {
    if (change.filename.endsWith('.js')) {
      worker.terminate()
      worker = new Worker('./app.js')
    }
  }
}

// All the folder to watch for
['./src', './lib', './test'].map(reloadOnChange)

这可能不是最好的解决方案,如果你使用javascript以外的任何东西,不依赖于一些构建过程。

const cleanCache = (moduleId) => {
    const module = require.cache[moduleId];
    if (!module) {
        return;
    }
    // 1. clean parent
    if (module.parent) {
        module.parent.children.splice(module.parent.children.indexOf(module), 1);
    }
    // 2. clean self
    require.cache[moduleId] = null;
};

最近(2009年)在node.js邮件列表中有一个关于这个主题的帖子。简短的回答是否定的,目前还不可能自动重载所需的文件,但一些人已经开发了添加此功能的补丁。