In Node, how do I need files inside eval?

I have two test.js and x.js in the same directory:

  • test.js :

     console.log(eval( "require('x.js')" )); 
  • x.js empty.

Expected : require returns undefined , so nothing is registered.

Actual : node test.js gives me Error: Cannot find module 'x.js' (stack multiplicity is omitted for brevity).

The situation is similar to this other question , with the differences that I used eval rather than new Function and require defined, it just unexpectedly works.


Why is this?

How to correctly require module in eval 'd code?

+5
source share
1 answer

In require() local file / module, the path should begin with . (same directory) or .. (parent directory) :

 console.log(eval( "require('./x.js')" )); 

Without any of these, Node looks for x.js as the main module or is contained in the node_modules directory .


If eval not indirectly referencing:

 var e = eval; // global eval e("require('./x.js')"); // ReferenceError: require is not defined 

It should evaluate the string in the current scope and be able to reference require .

+8
source

All Articles