我正在使用 contextify ( https://www.npmjs.com/package/contextify ) 在 Node 沙箱中运行异步“不受信任”脚本。同样的问题也适用于 Node 0.12+ vm.runInContext()。
Contextify = require('contextify');
rp = require('request-promise');
var myCode = "rp('http://www.google.com').then( function (htmlString) { RESULT = htmlString })"
defaultContext = { rp: rp, setTimeout : setTimeout, console: console }
vm = Contextify( defaultContext )
vm.run( myCode );
vm.RESULT
//undefined
是否有任何未记录的函数或事件可以让我知道虚拟机何时执行了所有操作? 或者有没有一种聪明的方法来包装这个请求 promise 函数,以便我在虚拟机之外收到消息?
最佳答案
只需创建一个匿名函数来处理要传递的回调。
Contextify = require('contextify');
rp = require('request-promise');
var myCode = "function(callback) { rp('http://www.google.com').then(callback); }"
defaultContext = { rp: rp, setTimeout : setTimeout, console: console }
vm = Contextify( defaultContext )
vm.run( myCode )(function(htmlString) {
// Do what you need here
});
但是,如果您真的不信任代码,我会创建一个辅助匿名函数来保护回调本身不被修改。
关于javascript - 使用 contextify 从 Node vm 内部返回异步结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37220247/