1

I've got a question regarding loading external files in node.

Basically I'm loading an external JSON file that contains some configuration, and this file is modified by an external process every 10 minutes. How can i reload this file every 10 minutes, without restarting node?

I've tried this solution:

delete require.cache['/home/conf/myfile.json']

but some people have advised against it. Can anybody help me?

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Giangi
  • 61
  • 1
  • 8

3 Answers3

4

At the end I changed my code and I now use fs.readFile to load my json file, instead of using a require.

I then used node-watch to check for changes in file and reload it.

Giangi
  • 61
  • 1
  • 8
2

Couple options. You could just use setInterval for 10 minutes and read the file in the callback. Otherwise you could use fs.watch and trigger the reload when the file actually changes.

update based on comment

If you're using require, it will only load the file once, regardless of how many times you're requiring it and there isn't really a mechanism to invalidate a required file. You could create a wrapper around the functionality and require that instead. Your wrapper is the file you require, and it exposes a function which returns your current config. Inside that module you could create the setTimeout refresh mentioned above.

Community
  • 1
  • 1
Timothy Strimple
  • 22,920
  • 6
  • 69
  • 76
0

You can have a look at my module-invalidate module that allows you to invalidate a required module. The module will then be automatically reloaded on further access.

Example:

module ./myModule.js

module.invalidable = true;
var count = 0;
exports.count = function() {

    return count++;
}

main module ./index.js

require('module-invalidate');

var myModule = require('./myModule.js');

console.log( myModule.count() ); // 0
console.log( myModule.count() ); // 1

setInterval(function() {

    module.constructor.invalidateByExports(myModule);

    console.log( myModule.count() ); // 0
    console.log( myModule.count() ); // 1

}, 10*60*1000);
Franck Freiburger
  • 26,310
  • 20
  • 70
  • 95