Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does require() in node.js work?

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!

like image 269
Trantor Liu Avatar asked Feb 28 '12 02:02

Trantor Liu


People also ask

How does require work in NodeJS?

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.

Why does NodeJS use require instead of import?

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 .

Why we use require in js?

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.

What does the require function return?

The require(...) function returns the module. exports value from the "required" module, and in the case its the Profile function.


1 Answers

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

like image 173
Andrey Sidorov Avatar answered Oct 11 '22 20:10

Andrey Sidorov