在 vm 脚本上下文中传递函数 [英] Pass functions in a vm script context
问题描述
假设我有一个看起来像这样的库模块:
Let's say I have a library module that looks like this:
module.exports = {
increment: function() {
count++;
}
}
我想在动态生成的脚本中使用它,如下所示:
And I'd like to use it in a dynamically generated script that looks like this:
(function() { lib.increment(); })();
通过在沙箱中传递它:
var sandbox = {
count: 1
lib: require('./lib')
}
var script = new vm.Script('(function() { lib.increment() })();');
script.runInNewContext(sandbox);
我遇到的明显问题是一方面我不能要求lib",因为count"没有在 lib.js 中定义;另一方面,如果我在lib.js"文件的导出上方定义 var count
,这个新的 count
变量将受到影响,而不是沙箱中的变量.
The obvious problem I run into is that I on the one hand can't require "lib" because "count" is not defined in lib.js ; on the other hand if I define var count
above the exports of the "lib.js" file, this new count
variable will be affected instead of the one in the sandbox.
以下是我想遵守的限制条件:
Here are the constraints that I would like to respect:
- 在生成的文件中使用 vm 而不是 eval() 或 require()
- 在外部文件中定义了lib"
- 没有修改自动生成的脚本,所以没有使用
lib.increment.apply(context)
或类似的
到目前为止我发现的唯一解决方案是将生成的脚本中的 lib
函数作为字符串添加,或者直接在 sandbox
对象上定义它们,我发现这是一个不太理想的选择.
The only solutions I've found so far is to prepend the lib
functions in the generated script as a string, or to define them directly on the sandbox
object, which I find to be a less desirable option.
似乎没有任何方法可以在 require
调用中传递变量上下文.
There doesn't seem to be any way of passing a context of variables on the require
call.
推荐答案
实现此目的的一种方法是让您的 lib
模块成为一个函数,该函数接受上下文然后返回正确的接口.
One way of accomplishing this is have your lib
module be a function that takes in a context then returns the correct interface.
lib.js
module.exports = function(context) {
var count = context.count;
return {
increment: function() {
count++;
}
};
};
main.js
var sandbox = {
count: 1
};
sandbox.lib = require('./lib')(sandbox);
var script = new vm.Script('(function() { lib.increment() })();');
script.runInNewContext(sandbox);
这篇关于在 vm 脚本上下文中传递函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!