Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hot reload external js file in node.js if there's any changes to the file

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.

like image 298
Tony Chen Avatar asked Oct 22 '22 00:10

Tony Chen


1 Answers

There is native support, although it isn't consistent across operating systems. That would be either using fs.watch(), or fs.watchFile(). The first function will use file change events, while the second one will use stat polling.

You can watch a file, and the check it's modification time when it has changed.

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

With fs.watchFile(), you don't need to use fs.stats() since the functions already callbacks instances of fs.Stat.

fs.watchFile(file, function(curr, prev) {
  if (curr.mtime.getTime() > loadTime) {
    // delete the cached file and reload
  } else {
    // return the cached file
  }
});
like image 134
hexacyanide Avatar answered Oct 23 '22 17:10

hexacyanide