Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs execute exported function from string

I want to know if it's possible to run a function that is named a string in nodejs. All this code is running on the server side with no browser appearance at all.

Assuming I export a file test.js with the following code

module.exports.test = function(x)
{
   console.log(x*5);
}

Can I do this somehow?

main.js

imp = require('test.js');
toExecute = "test";

// somehow call imp.test using toExecute`
like image 443
Kartik Avatar asked Sep 01 '26 21:09

Kartik


1 Answers

Sure:

imp[toExecute](5);

Logs 25.

like image 56
rfunduk Avatar answered Sep 03 '26 11:09

rfunduk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!