我正在使用以下脚本将字符串编译为模块。如何为此模块指定上下文,以便
myGlobal
在代码中可用?
const myGlobal = "Hello";
function compile(src) {
var m = new module.constructor;
m._compile(src, '');
return m.exports;
}
(async()=> {
const code = `
module.exports = async () => {
return myGlobal;
}
`;
const result = await compile(code)()
console.log(result)
})();
// ReferenceError: myGlobal is not defined
感谢您的评论,使我能够
vm
开始工作:
const vm = require('node:vm');
(async()=> {
const code = `
const got = require('got');
module.exports = async (data) => {
return myGlobal + ' ' + data;
}
`;
const context = { myGlobal: 'Hello', module: {}, require }
vm.createContext(context);
const script = new vm.Script(code)
const result = await script.runInContext(context)('John');
console.log(result)
})();