geeky_monster
geeky_monster

Reputation: 8792

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.

Upvotes: 0

Views: 1556

Answers (2)

Ahmet Can Güven
Ahmet Can Güven

Reputation: 5462

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

Upvotes: 1

LoveAndCoding
LoveAndCoding

Reputation: 7947

Node.js will cache calls to the same file so it doesn't have to fetch it again. To get the file as if it were new you'll need to clear the cache in require.cache. The key for the file should be the resolved name which you can look up with require.resolve()

Upvotes: 1

Related Questions