5

Is it possible to hot reload external js files in node.js based on its timestamp?

I know node.js caches module after first time load from here: http://nodejs.org/docs/latest/api/modules.html#modules_caching

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

And I also know if I need to reload it I can do like this:

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

But I wonder if there's any native support in node.js that it watches the file and reload it if there's any changes. Or I need to do it by myself?

pseudo code like

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

P.S. I am aware of supervisor and nodemon and don't want to restart server for reloading some specific modules.

4

1 回答 1

3

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

您可以观看一个文件,并在它发生更改时检查它的修改时间。

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
  }
});
于 2013-09-18T03:25:50.863 回答