evaluate statically-analyzable expressions
Branch: master
Clone or download
goto-bus-stop Merge pull request #22 from goto-bus-stop/warn
explicitly mention security caveats
Latest commit 42f6914 Feb 18, 2019
Type Name Latest commit message Commit time
Failed to load latest commit information.
example tests, docs Jul 21, 2013
test Modified FunctionExpression and CallExpression to be a bit more safe … Oct 5, 2017
.travis.yml badges Jul 21, 2013
LICENSE package.json etc Jul 21, 2013
index.js Fix sandbox breakout vulnerability Feb 14, 2019
package.json 2.0.1 Feb 15, 2019
readme.markdown explicitly mention security caveats Feb 15, 2019



evaluate statically-analyzable expressions

testling badge

build status


static-eval is like eval. It is intended for use in build scripts and code transformations, doing some evaluation at build time—it is NOT suitable for handling arbitrary untrusted user input. Malicious user input can execute arbitrary code.


var evaluate = require('static-eval');
var parse = require('esprima').parse;

var src = process.argv[2];
var ast = parse(src).body[0].expression;


If you stick to simple expressions, the result is statically analyzable:

$ node '7*8+9'
$ node eval.js '[1,2,3+4*5-(5*11)]'
[ 1, 2, -32 ]

but if you use statements, undeclared identifiers, or syntax, the result is no longer statically analyzable and evaluate() returns undefined:

$ node eval.js '1+2+3*n'
$ node eval.js 'x=5; x*2'
$ node eval.js '5-4*3'

You can also declare variables and functions to use in the static evaluation:

var evaluate = require('static-eval');
var parse = require('esprima').parse;

var src = '[1,2,3+4*10+n,foo(3+5),obj[""+"x"].y]';
var ast = parse(src).body[0].expression;

console.log(evaluate(ast, {
    n: 6,
    foo: function (x) { return x * 100 },
    obj: { x: { y: 555 } }


var evaluate = require('static-eval');

evaluate(ast, vars={})

Evaluate the esprima-parsed abstract syntax tree object ast with an optional collection of variables vars to use in the static expression resolution.

If the expression contained in ast can't be statically resolved, evaluate() returns undefined.


With npm do:

npm install static-eval