求助:node.js vm 模块在什么情况下使用?
发布于 10 年前 作者 hackerjs 9998 次浏览 最后一次编辑是 8 年前
//作了个vm 测试
var vm = require('vm'),
    code = 'var square = n * n;',
    fn = new Function('n', code),
    script = vm.createScript(code),
    sandbox;
n = 5;
sandbox = { n: n };
benchmark = function(title, funk) {
    var end, i, start;
    start = new Date;
    for (i = 0; i < 5000; i++) {
        funk();
    }
    end = new Date;
    console.log(title + ': ' + (end - start) + 'ms');
};
var ctx = vm.createContext(sandbox);
benchmark('vm.runInThisContext', function() { vm.runInThisContext(code); });
benchmark('vm.runInNewContext', function() { vm.runInNewContext(code, sandbox); });
benchmark('vm.runInContext', function() { vm.runInContext(code, ctx); });
benchmark('script.runInThisContext', function() { script.runInThisContext(); });
benchmark('script.runInNewContext', function() { script.runInNewContext(sandbox); });
benchmark('script.runInContext', function() { script.runInContext(ctx); });
benchmark('fn', function() { fn(n); });

vm.runInThisContext: 5ms vm.runInNewContext: 2799ms vm.runInContext: 1325ms script.runInThisContext: 5ms script.runInNewContext: 2585ms script.runInContext: 1373ms fn: 0ms

vm 模块在什么情况下使用呢

3 回复

正好刚接触到vm模块,简单说下: vm提供了一个沙箱环境,什么叫沙箱环境?类似于一个独立的执行空间,什么时候会用到vm模块?就以我现在接触的需求来说,每个月都有运营活动,但是每次需求又不同,比如一些优惠规则不同,最后可能只需要得到一个结果,如果每次活动都去修改代码就会显得很麻烦,我们提供一个后台管理界面,或者直接在数据库里写入每次活动的不同计算规则,这些规则其实也是JavaScript代码,既然是代码就需要执行才行。这就形成了一种情况:在已有的程序中插入一段代码进行执行,这要怎么实现?如果觉得很容易插入的话,那么是不是黑客可以在你的程序中插入一段代码执行呢?这当然是不允许的,所以就需要提供一种安全环境来执行——就是沙箱了,而vm模块就是提供了这样一种执行环境。

也可以用于模块封装

@hpgt 理解了谢谢

回到顶部