我想在 node 中运行第三方 JavaScript 文件(我对其内容没有太多控制权)并访问由该文件的代码在其上下文中创建的全局变量。
我考虑过两件事:
在
vm
中运行代码沙盒。问题是我不知道如何正确创建上下文,因为vm.createContext([sandbox])
不会自动为我想要运行的脚本提供基本的东西,例如console
或require
或任何东西。这有点令人失望,因为文档明确指出(强调我的):
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.
什么是“任何标准全局对象所具有的内置对象和函数”?我天真地假设它是
console
、process
、require
等。但如果是这样,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在 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/