Giter Site home page Giter Site logo

node-eval's Introduction

Eval - require() for module content!

Overview

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.

Benefits

Why would you be using the eval module over the nativerequire? Most of the time require is fine but in some situations, I have found myself wishing for the following:

  • Ability to supply a context to a module
  • Ability to load the module file(s) from non node standard places

Or simply to leverage JavaScript's eval but with sandboxing.

Download

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

npm install eval

Usage

var _eval = require('eval')
var res = _eval(content /*, filename, scope, includeGlobals */)

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
  • includeGlobals (Boolean): allow/disallow global variables (and require) to be supplied to the content (default=false)

Examples

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")', true)
// => res === require('events')

res = _eval('exports.x = process', true)
// => res.x === process

License

Here

node-eval's People

Contributors

chenxsan avatar decentralion avatar ericcornelissen avatar gastonprieto avatar jacobfischer avatar joaosamouco avatar josh-cena avatar markdalgleish avatar pierrec avatar reggi avatar ssimpo avatar xonev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

node-eval's Issues

react complains props is not a plain object

I have the following react code running in node.js:

let fn = _eval(
`
      var React = require("react");
      module.exports = function(props,el) {
         return React.createElement("div",{},"hello");
      }
`
, "eval", {}, true);
let component = React.createElement(fn, { name: "John" });           
let s = ReactDOMServer.renderToString(component);
console.log(s);

but react complains that

Warning: React.createElement(...): Expected props argument to be a plain object. Properties defined in its prototype chain will be ignored.

Does anybody knows why this is happening and is there something I can do?

Of course there is no warning if I execute outside of _eval. I should mention also that the above warning was introduced with facebook/react#6134

Import not working?

I tried to use an import statement instead of the require:

import * as _eval from 'eval';

But when using the module I get the error message _eval is not a function.

Unable to overwrite globals.

Here's an example where I'm requiring a file ./global.js Array.marker a property of a global variable is not being updated.

// file eval ./example.js
var _eval = require('eval')
var code = [
  'Array.marker = true',
  "require('./global.js')",
  'console.log(Array.marker)' // => true
].join('\n')

var fileName = __dirname + '/example.js'

_eval(code, fileName, {}, {
  'require': require
})
// file eval ./global.js
var hi = function () {
  Array.marker = false
}
module.exports = hi()

Is there any way to make it so that the required module edits the global value for Array.marker?

Note, I'm replacing requireLike with require. So we can see that it's not requireLike that is causing the issue.

Buffer is undefined with includeGlobals: true

Example (node v14.16.1):

const nodeEval = require('eval');
const test = nodeEval(`module.exports = () => console.log(typeof Buffer);`, 'test.js', {}, true);
test(); // > undefined

It seems this is because Buffer is non-enumerable, and we use Object.keys to merge global into sandbox, so Buffer gets left behind.

A few things like URL are being merged manually, perhaps the same could be done for Buffer?

Alternatively, we could use Object.getOwnPropertyNames(global) instead of Object.keys to avoid missing non-enumerable properties, though I don't know if this has any unintended side-effects. For now, I fixed it on my side by passing those as the scope (third argument).

Thanks!

trying to use require "path" error: The "path" argument must be of type string

❯ node --experimental-modules
Welcome to Node.js v16.3.0.
Type ".help" for more information.
> const _eval = require('eval', '.', {}, true)
undefined
> _eval("var expect = require('chai').expect", true)
Uncaught:
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received null
    at new NodeError (node:internal/errors:363:5)
    at validateString (node:internal/validators:119:11)
    at Object.dirname (node:path:1276:5)
    at new Module (node:internal/modules/cjs/loader:170:20)
    at requireLike (/Users/samueljoseph/Documents/Github/neurogrid/paironauts/node_modules/require-like/lib/require-like.js:5:22)
    at module.exports (/Users/samueljoseph/Documents/Github/neurogrid/paironauts/node_modules/eval/eval.js:44:23)
    at REPL2:1:1
    at Script.runInThisContext (node:vm:129:12)
    at REPLServer.defaultEval (node:repl:522:29)
    at bound (node:domain:416:15) {
  code: 'ERR_INVALID_ARG_TYPE'
}

any ideas?

I looked at the following issues:

but not sure what to try next ...

Getting Error ReferenceError: globalThis is not defined while using with Node 10.24.1

I have my node environment as 10.24.1 where I am facing this issue

evalmachine.<anonymous>:1
Object.getOwnPropertyNames(globalThis)

ReferenceError: globalThis is not defined
at evalmachine.<anonymous>:1:28
at Script.runInContext (vm.js:133:20)
at Script.runInNewContext (vm.js:139:17)
at Object.<anonymous> (C:\Users\NakulJhunjhunwala\Desktop\Node test\node_modules\eval\eval.js:17:4)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)

require not defined?

This seems like something aint right. Maybe it's because I'm running node v5 and it broke something?

It's showing the error [ReferenceError: require is not defined] for _eval on any code that contains require. Urgh.

Should not be logging.

I'm not sure whats causing this but when I run this, it logs the error below. The try should prevent any writing to stdout / stderr. This is really a pain. @pierrec any ideas on what could be causing it?

var _eval = require('eval')

try {
  _eval("require('missing-repo')", 'require-file.js', {}, true)
} catch (e) {

}

Logs this:


module.js:338
    throw err;

Module not found: Error: Cannot resolve module 'module'

nodejs version

6.9.1

npm version

3.10.8

issue description

when I use the module eval, the nodejs report the error:

ERROR in ./~/require-like/lib/require-like.js
Module not found: Error: Cannot resolve module 'module' in F:\projects\businessmap-app\node_modules\require-like\lib
 @ ./~/require-like/lib/require-like.js 1:13-30

TypeError: Cannot read properties of undefined (reading 'filename')

I noticed an error while using this package with Node.js v16.13.2 1. Specifically, when not providing a filename myself, I'm seeing the error:

.../node_modules/eval/eval.js:38
  var _filename = filename || module.parent.filename;
                                            ^

TypeError: Cannot read properties of undefined (reading 'filename')
    at module.exports (.../node_modules/eval/eval.js:38:45)
    at file:.../test.js:3:1
    at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:385:24)
    at async loadESM (node:internal/process/esm_loader:88:5)
    at async handleMainPromise (node:internal/modules/run_main:61:12)
View the test.js script
import jsEval from "eval";

jsEval("module.exports = { };");

This seems to me related to the fact that I'm using CommonJS code (namely this package) from ESModules code. Because ESModule doesn't use module, I'm guessing module.parent is undefined and hence the filename cannot be obtained.

The work-around is pretty simple (at least for now): just provide a filename. However, as the filename is optional in the API, I think it would make sense to find an alternative default filename to be used when none is provided - one that works when calling this package from ESModule code.

Also, see ericcornelissen/svgo-action#548 (comment) for more background information on how I encountered this problem.

Footnotes

  1. I did not try to figure out the exact version(s) of Node.js where this issue first happens.

The latest commit triggers an ReferenceError

The latest commit (527557a) add a line of code "sandbox.URL = URL", however URL is not defined before.

I use the plugin "static-site-generator-webpack-plugin" which uses your package in their code and I got the error today when I built my package.

ERROR in ReferenceError: URL is not defined
at module.exports (/home/circleci/repo/web_static/node_modules/eval/eval.js:59:17)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.