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?
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).
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With