Call function by (string) name on node.js


At the client side you do it via window["functionName"](arguments);. How it would be possible in node.js server-side code?

11/21/2011 1:50:45 AM

Accepted Answer

you're looking for global

Note, however, that in modules nothing is ever exposed to this level

11/21/2011 2:02:21 AM

If you need such a capability within a module, one hack is to store such module functions in variables within the module and then call them by accessing them from the module object properties. Example:

var x = { }; // better would be to have module create an object
x.f1 = function()
    console.log('Call me as a string!');

Now, within the module, you can call it using the value from a string:

var funcstr = "f1";

I am learning the ropes with Node myself, the above is probably all sorts of wrong :-). Perhaps a marginally better way to write this example would be (for the module m.js):

module.exports =
    f1: function() { console.log("Call me from a string!"); },
    f2: function(str1) { this[str1](); }

Now you can:

var m = require('m.js');

Or even just:

var m = require('m.js');


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow