Node.js Module Content Evaluator

0.1.8 · abandoned · verified Sun Apr 19

The `eval` package for Node.js provides a mechanism to evaluate JavaScript code strings as if they were standalone modules loaded via `require()`, but without necessitating a file path. It leverages Node.js's built-in `vm` module to create a sandboxed environment for execution. This allows developers to programmatically load and execute module content from non-standard locations or inject custom contexts and scopes into the evaluated code. A key feature is the ability to control access to global variables, including `require()` itself, through an `includeGlobals` option. The package is currently at version 0.1.8, indicating a very mature or, more likely, an inactive development status. Its release cadence is effectively dormant. It differentiates itself from a simple `eval()` by mimicking Node's module loading environment, making it suitable for scenarios requiring dynamic module-like code execution within a controlled environment.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates evaluating JavaScript code strings as modules, including exporting values, functions, accessing Node.js globals, and providing custom scopes.

const _eval = require('eval');

// Example 1: Evaluate a simple assignment and export
let res1 = _eval('var x = 123; exports.x = x');
console.log('Result 1 (simple export):', res1); // Expected: { x: 123 }

// Example 2: Evaluate a function export
let res2 = _eval('module.exports = function () { return 456 }');
console.log('Result 2 (function export call):', res2()); // Expected: 456

// Example 3: Evaluate with global access (e.g., process)
// Note: The `true` argument enables `includeGlobals`.
let res3 = _eval('exports.pid = process.pid', 'dummy.js', {}, true);
console.log('Result 3 (process.pid):', res3.pid); // Expected: current process ID

// Example 4: Evaluate with a custom scope
let customScope = { myVar: 'hello world' };
let res4 = _eval('exports.message = `The var is ${myVar}`', 'scope.js', customScope);
console.log('Result 4 (custom scope):', res4.message); // Expected: "The var is hello world"

view raw JSON →