javascript / expert
Snippet
Isolated Code Execution using node:vm Synthetic Context Frameworks
Node.js node:vm allows compiling and running scripts within isolated V8 synthetic context sandboxes with strict execution timeouts.
snippet.js
javascript
1
2
3
4
5
6
7
8
import vm from 'node:vm';const sandboxContext = vm.createContext({ console, result: null });const code = 'result = [1, 2, 3].map(x => x * 2);';const script = new vm.Script(code);script.runInContext(sandboxContext, { timeout: 100 });console.log(sandboxContext.result);
nodejs
Breakdown
1
import vm from 'node:vm';
Imports the Node.js V8 Virtual Machine execution module.
2
const sandboxContext = vm.createContext({ console, result: null });
Creates a sandboxed V8 execution context with explicit global bindings.
3
const code = 'result = [1, 2, 3].map(x => x * 2);';
Defines JS code string to evaluate inside sandbox.
4
const script = new vm.Script(code);
Pre-compiles the script string into executable V8 bytecode.
5
script.runInContext(sandboxContext, { timeout: 100 });
Executes pre-compiled script in context with a 100ms wall-clock CPU timeout.
6
console.log(sandboxContext.result);
Reads output variable mutated within sandbox scope.