Skip to content

Instantly share code, notes, and snippets.

@co3moz
Last active June 5, 2020 15:58
Show Gist options
  • Save co3moz/835f1925dab5dd4b9a74abd55c588df4 to your computer and use it in GitHub Desktop.
Save co3moz/835f1925dab5dd4b9a74abd55c588df4 to your computer and use it in GitHub Desktop.
Node.js template literal function for executing code in sandbox environment
import { js } from './js-literal';
// easy call
let result = js()`1`;
// auto context
let result2 = js()`${result}`;
assert(result === result2);
// auto context, objects
let a = { hello: true };
js()`${a}.hello = false`;
console.log(a.hello); // false
// runInContext parameters
try {
js({ timeout: 500 })`while(true) {}`;
} catch(e) {
console.log('timeout!!');
}
// context
js()`x = 1; this`; // { x: 1 }
// debug
let x = 10;
js({ debug: true })`x = ${x}; this`; // 'x = var_0; this'
js()`x = ${x}; this`; // { var_0: 30, x: 30 }
import vm from 'vm';
export function js(options?: string | vm.RunningScriptOptions) {
return (text: TemplateStringsArray, ...values) => {
const context = {};
const code = values.reduce((o, key, i) => {
let name = 'var_' + i;
context[name] = key;
o.push(name, text[i + 1]);
return o;
}, [text[0]]).join('');
if (options && options.debug) return code;
return vm.runInContext(code, vm.createContext(context), options);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment