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


当前回答

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

你不需要任何复杂的子进程产卵/杀死和管道性病进出…你只需要一个简单的网络工作者,这就是全部!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以外的任何东西,不依赖于一些构建过程。

其他回答

用这个:

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

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

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

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

这里有一个在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”。

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

我尝试过pm2:安装简单,使用也很方便;结果令人满意。但是,我们必须考虑我们想要哪个版本的pm2。PM 2运行时是免费版,而pm2 plus和pm2 enterprise则不是免费的。

至于Strongloop,我的安装失败或没有完成,所以我不能使用它。