Executing Node.js Function from an External File Dynamically

Is it possible to run a Node function from an external file that may be 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
}

When I run the code using 'node main.js'

After the code starts running, I update external.js to

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

Despite the change, it continues to display 'James' instead of 'Jack'. Is there a way to write the code so that the new function gets executed when the code is changed?

I require this functionality as I am creating a service where users can provide their own JavaScript files which are then executed when a specific function in the service is called depending on the user accessing it.

Answer №1

Make sure to clear the module cache before making each call.

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

function fetchExternalData(){
    var externalModule = require(moduleToRemove);
    var output = externalModule.result();
    console.log(output);
}

setInterval(function(){
    delete require.cache[moduleToRemove]; //clearing the cache
    fetchExternalData();
}, 3000);

Answer №2

In Node.js, repeated calls to the same file are cached to avoid unnecessary fetching. To retrieve the file as if it were fresh, you must clear the cache in require.cache. The file's key should be the resolved name, which can be found using require.resolve().

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discover the method to calculate the combined file size of multiple uploads with jquery

One of the challenges I'm facing is ensuring that users can only upload multiple files if the total size does not exceed 3GB. Is there a way I can enforce this limit? Below is the current code snippet I am using: var fileCount = 0; var showFileCo ...

Leveraging package-lock.json in version control systems

We are currently working on a React Native project and utilizing GitHub for version control. One of the main challenges we have been facing revolves around managing npm dependencies. Whenever we push our changes to the master branch, conflicts with the p ...

Error: Unable to convert Mongoose object to ObjectId

Currently tackling an issue with my small blog app and I seem to be stuck at this error- { "message": "Cast to ObjectId failed for value \" 597c4ce202ca9c353fc80e8a\" at path \"_id\" for model \"Blog\"", "name": "CastErr ...

Is there a method to store only a portion of the string object in async-storage?

Is there a way to save only part of the string object into async-storage? For example, if the "result.userPrincipalName" contains "[email protected]", I want to save only the "bob23". What is the best method to achieve this? await AsyncStorage.setIt ...

Creating a test suite with Jasmine for an Angular ui-grid component compiled without using $scope

I have encountered an issue while using $compile to compile a ui-grid for Jasmine testing. Initially, everything worked smoothly when I passed $scope as a parameter to the controller. However, I am now transitioning to using vm, which has resulted in $comp ...

Scrolling up or down in an HTML webpage using a script

Seeking a code snippet for my website that will allow me to achieve the following functionality: Upon clicking on text_head1, a list of lines should scroll down. Subsequently, when I click on text_head2, the previous list should scroll up while the new l ...

The method of altering a menu link in WordPress using jQuery varies according to whether the user is logged in or not

I need to update the last link on my menu. When a user is logged in, it should display a profile link; otherwise, it should show a sign-up link. ...

Saving the Chosen Option from Button Group into react-hook-form State

Struggling to save the chosen value from MUI Button Group into react-hook-form's state, but encountering challenges with the update not happening correctly. view codesandbox example Below is a simplified version of my code: import { ButtonGroup, But ...

`Trouble with detecting images using @tensorflow-models/mobilenet in a NodeJs environment`

I have developed an API where I need to perform checks for nudity, violence, and vulgarity before uploading images to AWS. I came across @tensorflow-models/mobilenet as a solution, but when I implemented the code, it resulted in a runtime error as shown be ...

The error message "Unexpected node environment at this time" occurred unexpectedly

I am currently watching a tutorial on YouTube to enhance my knowledge of Node.js and Express. To enable the use of nodemon, I made modifications to my package.json file as shown below: package.json "scripts": { "start": "if [[ $NODE_ENV == 'p ...

Deploying the app on Heroku and setting up the SSH key for secure

Having trouble pushing code to the Heroku server with this command $ heroku login Enter your Heroku credentials. Email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d8b2b9abb3b7bab098b0b7acb5b9b1b4f6bbb7b5">[email pr ...

Error when redirecting in Express due to invalid integer input syntax

After executing a PUT query in Postgres through Express, I encountered the following error message: Error: invalid input syntax for integer: "all-calls" This issue seems to be related to the line of code within the router.put function that says response. ...

React Prop Local Modal Redux

Just diving into the world of React and Redux, and I'm a bit lost on how to effectively utilize both local properties and redux properties simultaneously. After trying different approaches without success, I'm reaching out for guidance. My goal i ...

Currently experimenting with Laravel jetstream but encountering difficulties while running the command "npm run dev"

When trying to run npm run dev, I encountered the following error: [webpack-cli] TypeError: this.program.configureOutput is not a function at new WebpackCLI (/home/vagrant/sites/ecom/node_modules/webpack-cli/lib/webpack-cli.js:19:22) at runCLI (/home/vagr ...

Converting canvas illustrations into HTML files

I am in the process of creating a drawing application that will be able to export into HTML/CSS/JavaScript. I plan to use this tutorial as a foundation for the drawing functionality. My goal is to take all the rectangles within the this.shapes = [] array a ...

Having trouble installing python modules in heroku using python-shell

I am encountering an issue while attempting to integrate a python file into my node web application. Despite functioning properly on my local machine, once uploaded to Heroku, the modules fail to import correctly, resulting in the error message: ModuleNotF ...

Ways to prevent the jQuery simple slider from transitioning slides while it is in an invisible state

There is a jQuery slider on my website that behaves strangely when I navigate away from the Chrome browser and return later. It seems to speed through all pending slides quickly when it was not visible. Now, I want the slider to pause when it becomes invi ...

unable to process the build compilation

Can you help me figure out what's wrong? I used the create-react-app command to build this project. Here is the content of my package.json file: "name": "front", "version": "1.0.0", "private": true, "proxy": "http://127.0.0.1:8000", "dependencies": { ...

What are the steps to successfully launch a React SSR application on Heroku?

I am currently working on a basic React Server Side App. You can find the repository on GitHub. In my local environment, I've set up a build script that runs using npm start to initiate both client and server builds, along with a watcher for file chan ...

What is the best way to have a variable adjust each time a coin is inserted until it reaches a specific value?

I have developed a unique coin box that recognizes the value of each coin inserted. Users can now pay for a service that costs 2.0 € by inserting coins of various denominations such as 2.0 €, 1.0 €, 0.50 €, 0.20 €, and 0.10 €. In my react-nati ...