在节点中热重载外部 js 文件.js如果文件有任何更改



是否可以根据时间戳在node.js中热重载外部js文件?

我知道node.js在第一次加载后从这里缓存模块:http://nodejs.org/docs/latest/api/modules.html#modules_caching

模块在首次加载后缓存。这意味着 (除其他外)每次调用require('foo')都会得到 返回完全相同的对象,如果它将解析为相同的对象 文件。

我也知道如果我需要重新加载它,我可以这样做:

// first time load
var foo = require('./foo');
foo.bar()
...
// in case need to reload
delete require.cache[require;.resolve('./foo')]
foo = require('./foo')
foo.bar();

但我想知道 node 中是否有任何本机支持.js它会监视文件并在有任何更改时重新加载它。还是我需要自己做?

伪代码,如

// during reload
if (timestamp for last loaded < file modified time)
    reload the file as above and return
else
    return cached required file

附言我知道主管和nodemon,并且不想重新启动服务器以重新加载某些特定模块。

有本机支持,尽管它在操作系统之间不一致。那要么使用 fs.watch() ,要么使用 fs.watchFile() 。第一个函数将使用文件更改事件,而第二个函数将使用统计信息轮询。

您可以观看文件,并在文件更改时检查其修改时间。

var fs = require('fs');
var file = './module.js';
var loadTime = new Date().getTime();
var module = require(file);
fs.watch(file, function(event, filename) {
  fs.stat(file, function(err, stats) {
    if (stats.mtime.getTime() > loadTime) {
      // delete the cached file and reload
    } else {
      // return the cached file
    }
  });
});
使用

fs.watchFile() ,您不需要使用 fs.stats() 因为函数已经回调了 fs.Stat 的实例。

fs.watchFile(file, function(curr, prev) {
  if (curr.mtime.getTime() > loadTime) {
    // delete the cached file and reload
  } else {
    // return the cached file
  }
});

最新更新