javascript - 在单独的上下文中运行 js 代码并访问其全局变量

标签 javascript node.js

我想在 node 中运行第三方 JavaScript 文件(我对其内容没有太多控制权)并访问由该文件的代码在其上下文中创建的全局变量。

我考虑过两件事:

  1. vm 中运行代码沙盒。问题是我不知道如何正确创建上下文,因为 vm.createContext([sandbox])不会自动为我想要运行的脚本提供基本的东西,例如 consolerequire 或任何东西。

    这有点令人失望,因为文档明确指出(强调我的):

    If given a sandbox object, will "contextify" that sandbox so that it can be used in calls to vm.runInContext() or script.runInContext(). Inside scripts run as such, sandbox will be the global object, retaining all its existing properties but also having the built-in objects and functions any standard global object has.

    什么是“任何标准全局对象所具有的内置对象和函数”?我天真地假设它是 consoleprocessrequire 等。但如果是这样,API 不起作用,因为那些没有设置。我可能在这里误解了一些东西。

    var sandbox = vm.createContext({foo: 'foo'});
    var code = 'console.log(foo);';
    vm.runInContext(code, sandbox);
    

    结果:

    evalmachine.:1
    console.log(foo);
    ^
    ReferenceError: console is not defined

  2. child process 中运行代码.但我找不到任何有关访问子进程全局变量的文档。我假设与子进程通信的唯一方法是通过消息传递,但即使这似乎是从父进程到子进程,而不是相反...

基本上,我被困住了。停下来。

最佳答案

您可以使用 advanced vm/sandbox for Node.js

var VM = require('vm2').NodeVM; // https://github.com/patriksimek/vm2#nodevm

var options = {
    console: 'inherit',
    sandbox: {
        foo: 'foo'
    }
}

vm = new VM(options);

var code = `
    console.log(foo); 
    oldFoo = foo; 
    foo = Math.random();
`;

vm.run(code);

console.log(vm.context.oldFoo, vm.context.foo);

关于javascript - 在单独的上下文中运行 js 代码并访问其全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36861852/

相关文章:

javascript - 无法纠正错误 "Fail 1 - Table tag should have 3 rows and check with the requirements for CSS for table and tr"

javascript - 使用 JavaScript 进行日期和时间字符串操作

javascript - 计算困难的 [JavaScript] 问题?

javascript - 使用 JEST 测试 DOM 元素

node.js - Heroku 上的 nodemon 启动错误

javascript - JS 中迭代对象数组和键值

javascript - 为什么用构造函数创建对象会执行JavaScript中对象的方法?

javascript - Access-Control-Allow-Origin 不起作用 Google Cloud Functions GCF

javascript - Selenium - 计算具有匹配类的元素数

node.js - 如何使用nodejs获取sequelize关联中的单个对象