2
最近运行的代码的结果,我一直在尝试使用软件包来实现沙箱执行VM2已经由@Patrik西梅克出版如何获得这是由节点VM2
我试图运行一些js代码,我认为它是一个定制逻辑,我将这个逻辑存储在一个字符串变量中。
我需要在沙盒环境中执行此自定义逻辑(因为这是不可信的代码),并根据此结果取回实际环境中的响应以继续正常的应用程序流。
我尝试了几种方法来获得最终结果。自定义逻辑正在沙盒内成功执行,但我无法找到将此结果发回主进程的方式,但我得到的结果为undefined。所以,到目前为止没有任何工作。
希望我在这里得到一些答案。
定制逻辑(其将被存储在字符串内)
function addValues(a,b){
var c = a + b;
console.log('Addition of 2 values');
console.log(c);
return c;
}
addValues(10,10); // function call
实际实施
// vm2
const {NodeVM} = require('vm2');
const vm = new NodeVM({
console: 'inherit',
sandbox: {},
require: {
external: true,
builtin: ['fs','path'],
root: "./",
mock: {
fs: {
readFileSync() { return 'Nice try!';}
}
},
wrapper : ""
}
});
// Sandbox function
let functionInSandbox = vm.run("module.exports = function(customLogic){
customLogic //need to execute this custom logic
});
// Make a call to execute untrusty code by passing it as an argument
// to sandbox environment and obtain the result
var resultOfSandbox = functionInSandbox(customLogic);
console.log("Result of Sandbox :");
console.log(resultOfSandbox); // undefined (need to get the result of custom logic execution)
感谢您的回应。您的建议完美适用于检索执行结果。但是,就我而言,**自定义逻辑**是一种将被动态获取的东西,因此它不会被修改。例如:“将sandbox变量(ext)分配给函数调用,就像你所建议的那样”**(即:ext.exports = addValues(10,10);)**。有没有其他方法可以执行逻辑,并检索其结果? –