I tried this:
// mod.js var a = 1; this.b = 2; exports.c = 3; // test.js var mod = require('./mod.js'); console.log(mod.a); // undefined console.log(mod.b); // 2 console.log(mod.c); // 3, so this === exports?
So I image that require() may be implement like this:
var require = function (file) { var exports = {}; var run = function (file) { // include "file" here and run }; run.apply(exports, [file]); return exports; }
Is that right? Please help me to understand require(), or where can I find the source code. Thanks!
In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.
One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file. To use the require() statement, a module must be saved with . js extension as opposed to .
The require() method is used to load and cache JavaScript modules. So, if you want to load a local, relative JavaScript module into a Node. js application, you can simply use the require() method.
The require(...) function returns the module. exports value from the "required" module, and in the case its the Profile function.
Source code is here. exports
/require
are not keywords, but global variables. Your main script is wrapped before start in a function which has all the globals like require
, process
etc in its context.
Note that while module.js itself is using require()
, that's a different require function, and it is defined in the file called "node.js"
Side effect of above: it's perfectly fine to have "return" statement in the middle of your module (not belonging to any function), effectively "commenting out" rest of the code
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