vm is similar to eval(), but eval() can change the surrounding context, whereas vm cannot
vm is like creating a sandbox, the code will be executed in the different namespace instead of running in the current namespace.
var vm = require( 'vm' )
vm.runInThisContext( "1+1+1" )
//3
The difference:
var localVar = 123,
usingscript, evaled,
vm = require('vm');
usingscript = vm.runInThisContext('localVar = 1;',
'myfile.vm'); //'myfile.vm' is only for generating appropriate error msg
console.log('localVar: ' + localVar + ', usingscript: ' +
usingscript);
evaled = eval('localVar = 1;');
console.log('localVar: ' + localVar + ', evaled: ' +
evaled);
// localVar: 123, usingscript: 1
// localVar: 1, evaled: 1
create and run in context:
var vm = require( 'vm');
var context = { alphabet:""};
vm.runInNewContext( "alphabet += 'a'", context);
vm.runInNewContext( "alphabet += 'b'", context);
console.log( context );
Compiling code into a script with vm
example.js:
console.log( output )
var vm = require( 'vm' );
var fs = require( 'fs' );
var code = fs.readFileSync( 'example.js' );
console.log( code.toString());
var script = vm.createScript( code );
//script.runInNewContext( { output:"Kick Ass" }); undefined:1:1
script.runInNewContext( { "console":console, "output": "Kick Ass" });
output:
console.log( output )
Kick Ass