如何为 NodeJS 模块指定上下文

问题描述 投票:0回答:1

我正在使用以下脚本将字符串编译为模块。如何为此模块指定上下文,以便

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
javascript node.js es6-modules
1个回答
0
投票

感谢您的评论,使我能够

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)
})();

© www.soinside.com 2019 - 2024. All rights reserved.