Reuse a Node vm sandbox and delete the global state updates

35 views
Skip to first unread message

LPG

unread,
Aug 11, 2016, 8:34:40 PM8/11/16
to nodejs
I'm looking for a way to efficiently create a Node vm sandbox context which can be quickly reused for the purposes of running unsafe code sequentially. 

In my tests, setting-up and disposing of Node vm sandboxes is quite expensive in CPU and memory. A way around this would be to reuse a default sandboxed environment. However reusing a vm context causes the globals to persist. See example below ( adapted from the Node documentation) : 

    
    var util = require('util');
    var vm = require('vm');
    var _ = require('lodash');
    
    var context = { globalVar: 1 };
    var sandbox = vm.createContext(context);
    // sandbox = _.cloneDeep(sandbox) // fails with TypeError: needs a 'context' argument.

    console.log('sandbox before', sandbox);
    
    for (var i = 0; i < 10; ++i) {
      vm.runInContext('globalVar *= 2;', sandbox);
    }
    console.log(util.inspect(sandbox));
    
    // { globalVar: 1024 } // The global variable is incremented on each loop instead of being disposed.
   // would like an output of { globalVar: 2 }

I would like a method where the result is globalVar === 2 , ie. it gets reset on every iteration of the loop.
    
I even tried a lodash cloneDeep, which so I could reuse the context object, but no luck.

The goal is to have a cheap reusable clean default sandbox on every run. That is: it should have a lower cpu and memory profile versus creating a new context from scratch every time.
Reply all
Reply to author
Forward
0 new messages