Last active
June 5, 2020 15:58
-
-
Save co3moz/835f1925dab5dd4b9a74abd55c588df4 to your computer and use it in GitHub Desktop.
Node.js template literal function for executing code in sandbox environment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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