Update module at runtime

I am considering connecting a high res (high traffic) socket based architecture from .NET to Node.JS using Socket.IO.

My current system is developed in .NET and uses some scripting languages ​​loaded at runtime, so I can make hot fixes if needed by issuing a reload command to the server without having to restart various server / dispatcher processes.

I originally built it in such a way that, as I said, I can make hot fixes if needed, and also keep the system available with transparent fixes.

I'm new to Node.JS, but this is what I want to accomplish:

  • Load javascript files on demand at runtime, store them in variables somewhere, and call script functions.

What's the best solution? How can I call a specific function from a javascript file loaded at runtime as a string? Can I load the javascript file, store it in a variable, and call the functions in the usual way as required?

Thank!

+3


source to share


2 answers


If I understand your question correctly. You can check the vm module .

Or, if you want to reload required

files, you have to clear the cache and reload the file, something this package might do. Check the code, you get this idea.

Modules are cached after the first time they are loaded. This means (by the way) that every call that requires ('foo') will get exactly the same object returned if it resolves to the same file.

Multiple calls requiring ('foo') cannot cause module code to be executed multiple times. This is an important feature. With this, "partially executed" objects can be returned, allowing dependencies to be loaded even if they will call for loops.

More information can be found here .



  • Remove the cached module:

    delete require.cache[require.resolve('./mymodule.js')]
    
          

  • Claim it again. (perhaps require

    inside a function that you can call)

Update

Someone I know takes a similar approach. You can find the code here.

+6


source


You can take a look at my module-invalidate module which will allow you to invalidate the 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++;
}

      

The main module ./index.js

require('module-invalidate');

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

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

mySystem.on('hot-reload-requested', function() {

    module.invalidateByPath('./myModule.js'); // or module.constructor.invalidateByExports(myModule);
    console.log( myModule.count() ); // 0
    console.log( myModule.count() ); // 1
});

      

0


source







All Articles