Gangmax Blog

"require" in "node.js"

From here.

What does “require” do?

The basic functionality of require is:

  1. it reads a JavaScript file,

  2. executes the file,

  3. and then proceeds to return the exports object. An example module:

1
2
3
4
5
6
7
8
9
10
11
console.log("evaluating example.js");

var invisible = function () {
console.log("invisible");
}

exports.message = "hi";

exports.say = function () {
console.log(exports.message);
}

So if you run var example = require(‘./example.js’), then example.js will get evaluated and then example be an object equal to:

1
2
3
4
{
message: "hi",
say: [Function]
}

How does “require” find the target file?

1
2
3
4
5
6
7
8
9
10
if (path.startsWith('./')) {
// Load the local file in the relative path.
} else if (path.startsWith('/')) {
// Load the local file in the absolute path.
} else if (core module?) {
// Load the core module.
} else if (node_modules?) {
// load from the "node_modules" directory.
}
// NOTE: you can omit ".js" and require will automatically append it if needed.

For more detailed information, see the official docs.

Comments