如何在运行时在Node.js中加载模块?

时间:2019-02-19 06:29:00

标签: node.js

我有一个Node.js服务,我们称之为 服务A 。用户可以通过 服务A 访问我的网站。

我想拥有这样的功能,即不同的用户可以在我的网站上看到不同的内容。为此, 服务A 应该能够根据用户的配置执行不同的代码脚本(节点模块)。

由于脚本(节点模块)经常更新,因此我不想将它们存储在 服务A 中。因此,这里有一个 Service B ,它的功能是存储所有脚本(节点模块)。 服务A 可以将用户的配置发送到 服务B 服务B 会将相应的脚本(节点模块)返回到 服务A 。因此,在 服务A 中,我想要以下代码:

http.get('http://urlToServiceB?userConfig=' + userConfig, (resp) => {
    resp.on('data', (scriptInString) => {
        // Here I got the script in string, I would like to load the module from it.
        // Expect something like following:
        var moduleFromScript = myRequire(scriptInString);
        moduleFromScript.myfunction();
        ...
    });
})

如何实现 myRequire 函数?是否有任何开源库?非常感谢!

0 个答案:

没有答案