dontknow dontknow - 1 year ago 49
Javascript Question

Running Nodejs Function from Dynamic External File

I want to know if there is a way to run a Node function from an external file which is subject to change.

Main.js

function read_external(){
var external = require('./external.js');
var result = external.result();
console.log(result);
}

setInterval(function(){
read_external();
},3000);


External.js ( Initial )

exports.result = function(){
return "James"; // Case 1
}


I now run the code by typing node main.js

After the code starts running, I changed the External.js to

exports.result = function(){
return "Jack"; // Case 2
}


However inspite of the change, it keeps printing James and not Jack.
Is there a way to write the code such a way that the new function gets executed when the code is changed ?

I need this as I am building a service where people can provide their own scripts as JS files and it gets executed when they call a certain function in the service depending on who is calling it.

Answer Source

You can remove the module from cache before each call.

var module = require.resolve('./external.js');

function read_external(){
    var external = require(module);
    var result = external.result();
    console.log(result);
}

setInterval(function(){
    delete require.cache[module]; //clear cache
    read_external();
},3000);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download