gpt4 book ai didi

node.js - Require() 从字符串到对象

转载 作者:太空宇宙 更新时间:2023-11-03 23:30:05 24 4
gpt4 key购买 nike

假设我有一个字符串中的js文件的内容。此外,假设它有一个 exports['default'] = function() {...} 和/或其他导出的属性或函数。有什么方法可以将该字符串“要求”(将其编译)为对象,以便我可以使用它? (另外,我不想像 require() 那样缓存它。)

最佳答案

这是一个非常简单的示例,使用 vm.runInThisContext() :

const vm = require('vm');

let code = `
exports['default'] = function() {
console.log('hello world');
}
`

global.exports = {}; // this is what `exports` in the code will refer to
vm.runInThisContext(code);

global.exports.default(); // "hello world"

或者,如果您不想使用全局变量,您可以使用 eval 实现类似的效果:

let sandbox     = {};
let wrappedCode = `void function(exports) { ${ code } }(sandbox)`;

eval(wrappedCode);

sandbox.default(); // "hello world"

这两种方法都假设您提供给它的代码是“安全的”,因为它们都允许运行任意代码。

关于node.js - Require() 从字符串到对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39258000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com