notevil
Evalulate javascript like the built-in javascript eval()
method but safely.
This module uses esprima to parse the javascript AST then walks each node and evaluates the result.
Like built-in eval
, the result of the last expression will be returned. Unlike built-in, there is no access to global objects, only the context that is passed in as the second object.
Built in types such as Object
and String
are still available, but they are wrapped so that any changes to prototypes are contained in the eval instance.
Example
var safeEval = // basic mathvar result = console // 6 // context and functionsvar result = console // 107 // multiple statements, variables and if statementsvar result = console // dogs // inner functionsvar result = console // [100, 200, 300, 400]
Updating context from safeEval
var context = x: 1 obj: y: 2 // update context globalconsole // 300 // update property on objectconsole // 300
Creating functions
var func = safeEvalvar result = console // 200
Tracing errors
A .trace
property is available on error objects generated by code running inside of the sandbox. It contains an array containing the esprima node stack which has a loc
property, allowing you to get the line and column where the error occurred.
try {
safeEval('throw "some error"')
} catch (ex) {
ex.trace //=> [...esprimaAstTrace]
ex.trace[0].loc.start.line //=> 1
}