Nodejs 从字符串执行导出的函数

Nodejs execute exported function from string

本文关键字:函数 执行 字符串 Nodejs      更新时间:2023-09-26

我想知道是否可以在nodejs中运行一个名为字符串的函数。所有这些代码都在服务器端运行,根本没有浏览器外观。

假设我使用以下代码导出文件test.js

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

我可以以某种方式做到这一点吗?

主.js

imp = require('test.js');
toExecute = "test";
// somehow call imp.test using toExecute`

当然:

imp[toExecute](5);

日志25 .