0

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.

1
  • 1
    delete require.cache[require.resolve('./external.js')] might be your solution? Just tested and added my comment as an answer. Commented Jul 27, 2017 at 14:34

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

@dontknow You'r welcome :) Just made a little refactoring, please use the latest version.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.