Skip to content

Instantly share code, notes, and snippets.

@0ex-d
Created November 27, 2022 15:06
Show Gist options
  • Save 0ex-d/8ec6fd8e5a6e748bd7e31c10c69bc121 to your computer and use it in GitHub Desktop.
Save 0ex-d/8ec6fd8e5a6e748bd7e31c10c69bc121 to your computer and use it in GitHub Desktop.
Create a context for executing code in a sanbox using Node.js runtime Package: https://nodejs.org/docs/latest-v18.x/api/vm.html
// https://nodejs.org/docs/latest-v18.x/api/vm.html
const vm = require("vm");
// create an object in heap
const sandboxCtx = {};
// Contextify the sandbox.
vm.createContext(sandboxCtx);
let code = 'var human = 2; let fish = "a big fish :)"';
// no support for let, const keywords so replace
code = code.replace(/let|const/, "var");
// run the code: Note: "vm" module does not gurantee safety
// see "vm2" [https://github.com/patriksimek/vm2] for more safe alternative
// especially when getting input from user :(
vm.runInContext(code, sandboxCtx);
console.log(sandboxCtx);
// https://nodejs.org/docs/latest-v18.x/api/vm.html
const vm = require("vm");
// create an object in heap
// key/value gets updated in sandbox
const sandboxCtx = {fish: "a small fish"};
// Contextify the sandbox.
vm.createContext(sandboxCtx);
let code = 'var human = 2; let fish = "a big fish :)"';
// no support for let, const keywords so replace
code = code.replace(/let|const/, "var");
// run the code: Note: "vm" module does not gurantee safety
// see "vm2" [https://github.com/patriksimek/vm2] for more safe alternative
// especially when getting input from user :(
vm.runInContext(code, sandboxCtx);
console.log(sandboxCtx);
console.log(sandboxCtx.fish) // a big fish :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment