javascript / expert
Snippet
Secure Sandboxing with node:vm
The 'node:vm' module allows you to compile and run code within a separate V8 Virtual Machine context. This is essential for executing untrusted scripts or creating plugin systems where you need to isolate the global scope of the executing code from your main application.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
import vm from 'node:vm';const sandbox = { externalData: 10, result: 0 };vm.createContext(sandbox);const code = 'result = externalData * 2; var internal = 5;';vm.runInContext(code, sandbox);console.log(sandbox.result); // 20console.log(sandbox.internal); // 5
nodejs
Breakdown
1
vm.createContext(sandbox);
V8-ifies the object to serve as the global context for the VM.
2
vm.runInContext(code, sandbox);
Executes the string as JavaScript code inside the provided sandbox context.