Sandboxing In Node.JS Using VM Module
Two commonly known ways to execute a script in Node.JS are using eval () function or running it using VM module.
Lets see this through an example:
[js]
var vm = require(‘vm’);
this.name = "Sakshi";
var script = "this.name = ‘Tyagi’", withVM, withEVAL;
withEVAL = eval(script);
console.log("withEVAL :" + withEVAL + ", " + "local :"+ this.name);
withVM = vm.runInThisContext(script);
console.log(" withVM :" + withVM + ", "+ "local :"+ this.name);
[/js]
Here, we have executed a piece of JavaScript code in two ways:-
1. With eval() = eval() function passes a string to the JavaScript compiler and execute it. But at the same time, its not safe way to execute a script because it compromises the security of the application. eval() has access to all local as well as global objects.
In this case output will be:
withEVAL :Tyagi, local :Tyagi
2. With vm module = VM provides an access to V8 virtual machine in which the script can be executed. Running script does not have access to local objects. So in this way vm.runInThisContext
creates its own environment where only global objects can be used, thereby not effecting or accidentally modifying local objects.
In this case output will be:
withVM :Tyagi, local :Sakshi
So in this way, VM module can be used to sandbox our application having crucial data.