eval

Evaluate node require() module content directly

Eval - require() for module content!

This module is a simple way to evaluate a module content in the same way as require() but without loading it from a file. Effectively, it mimicks the javascript evil eval function but leverages Node's VM module instead.

It is published on node package manager (npm). To install, do:

npm install eval
var _eval = require('eval')
var res = _eval(content /*, filename, scope, noGlobals */)

The following options are available:

  • content (String): the content to be evaluated
  • filename (String): optional dummy name to be given (used in stacktraces)
  • scope (Object): scope properties are provided as variables to the content
  • noGlobals (Boolean): allow/disallow global variables to be supplied to the content (default=true)
var _eval = require('eval')
var res = _eval('var x = 123; exports.x = x')
// => res === { x: 123 } 
 
res = _eval('module.exports = function () { return 123 }')
// => res() === 123 
 
res = _eval('module.exports = require("events")')
// => res === require('events') 
 
res = _eval('exports.x = process')
// => res.x === process 

Here