Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Node, how do I require files inside eval?

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

  • test.js:

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

Expected: require returns undefined, so nothing is logged.

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

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


Why is this?

How do I correctly require a module in eval'd code?

like image 492
Anko Avatar asked May 09 '15 14:05

Anko


People also ask

How do I use require in NodeJS?

You can think of the require module as the command and the module module as the organizer of all required modules. Requiring a module in Node isn't that complicated of a concept. const config = require('/path/to/file'); The main object exported by the require module is a function (as used in the above example).

What is __ filename in NodeJS?

The __filename represents the filename of the code being executed. This is the resolved absolute path of this code file. For a main program, this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file.

How do I display the contents of a file in NodeJS?

Using Clean architecture for Node. We can use the 'fs' module to deal with the reading of file. The fs. readFile() and fs. readFileSync() methods are used for the reading files.

How add require in JavaScript?

To include the Require. js file, you need to add the script tag in the html file. Within the script tag, add the data-main attribute to load the module. This can be taken as the main entry point to your application.


1 Answers

To require() a local file/module, the path should start with . (same directory) or .. (parent directory):

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

Without either of those, Node looks for x.js to be a core module or contained in a node_modules directory.


Unless eval is referenced indirectly:

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

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

like image 193
Jonathan Lonowski Avatar answered Sep 22 '22 11:09

Jonathan Lonowski