0

This is how I dynamically add a function to the window object at run-time:

(function (myPluginModuleLib, $, undefined) {
    myPluginModuleLib.myModuleMethod =  (varArgs) => {
        console.log('Dynamic Call :  ' + varArgs);
    };
}(window.myPluginModuleLib = window.myPluginModuleLib || {}, jQuery));  

Then I can globally call it at any time :

window.myPluginModuleLib.myModuleMethod('HELLO WORLD PARAMS!');  

Is there a similar way to do this in NodeJs? I would like to add a function into memory. For exaple, in the main app.js, so that I could call it on demand, instead of always constructing it from a String:

let myModuleMethodString = 'var myModuleMethod = (varArgs) => { console.log("Dynamic Call : " + varArgs) }';
myModuleMethodString = myModuleMethodString.slice(myModuleMethodString.indexOf("{") + 1, myModuleMethodString.lastIndexOf("}"));

let myModuleMethod = new Function("varArgs", 'console.log("Dynamic Call : " + varArgs)');

try {
    myModuleMethod('HELLO WORLD PARAMS!');
} catch (error) {
    console.log(error);
}

Thank you all in advance.

3
  • Why do you think you can't do it similar to how you do it in the browser? It's still JavaScript.... Commented Oct 4, 2020 at 7:44
  • In the browser I attach it to the window object. How do I do that in Node, server side? Commented Oct 4, 2020 at 7:45
  • @Program-Me-Rev, you cannot attach to window which is running in your browser (client) from Node.js code running on your server. It has to be done on the client code. Commented Oct 4, 2020 at 7:59

2 Answers 2

1

If you want to stay with this solution, then you can use the global namespace in Node JS, what is similar to the window in the browsers, although it is not suggested to use globals.

Example:

global.myPluginModuleLib = {
    myModuleMethod : (varArgs) => {
        console.log('Dynamic Call :  ' + varArgs);
    }
};
global.myPluginModuleLib.myModuleMethod('HELLO WORLD PARAMS!');  

Sign up to request clarification or add additional context in comments.

Comments

1

short answer: you can just use "global" instead of "window". More info here: https://stackabuse.com/using-global-variables-in-node-js/

Long answer: this is not something you should ever do in Node.js. This just pollutes the global context. All your functions should always be defined within the context of a specific module

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.