我有节点脚本和后端,脚本包含某些数据,并且从后端获得了一些条件。
例如node script
:
var data={
count: 10,
length: 27,
days: 3
};
var condition = 'count > 10 && length < 3'; // <=== this condition got from backend
if( ... condition ...) {
// action 1
} else {
// action 2
}
我可以在没有eval
的情况下获得条件结果吗?因为来自后端评估的数据对服务器不安全。或者有没有办法在沙盒中运行这种情况?
我的解决方案是带有runInNewContext
的简单函数,条件使用我的变量在安全隔离的沙箱中运行
var vm = require("vm");
function safeEval(code, variables = {}, opts) {
var sandbox = Object.assign({
_code_result_: undefined
}, variables);
vm.runInNewContext('_code_result_=(' + code + ')', sandbox, opts);
return sandbox['_code_result_'];
}
var data = {
count: 10,
length: 27,
days: 3
};
var condition = 'count >= 10 && length > 3'; // <=== this condition got from backend
if (safeEval(condition, data)) {
// action 1
} else {
// action 2
}
使用一些评论,这样的东西可能会对您有所帮助?
var data = {
count: 11,
length: 27,
days: 3
};
var fromServer = [{field: 'count', operator: '>', value: '10'}, {field: 'length', operator: '>', value: '3'}];
if (checkObjConditions(fromServer)) {
console.log("yes");
} else {
console.log("no");
}
function checkObjConditions(co) {
//var conditions = c.split("&&");
var isCondition = true;
for (var a = 0; isCondition && a < co.length; a++) {
//var c = conditions[a].trim().split(",");
var r = compare(co[a]['field'], co[a]['operator'], co[a]['value']);
console.log(">", r);
if (!r)
isCondition = false;
}
return isCondition;
}
function compare(a, operator, b) {
var ans = false;
switch (operator) {
case '<':
if (data[a] < parseInt(b))
ans = true;
break;
case '>':
console.log(data[a], parseInt(b))
if (data[a] > parseInt(b))
ans = true;
break;
// ... and other cases also
}
return ans;
}