Search code examples
node.jsrequire

How does node.js require method interpret relative paths?


I'm having trouble understanding how node's require method is able to resolve relative paths.

Let's say I have a file structure like this:

root
|--- main.js
|
|--- importantUtilities.js
|
|--- apps
     |
     |--- app1.js

If both /root/main.js and /root/apps/app1.js want to require /root/importantUtilities.js, they parameterize the require function differently:

// File: /root/main.js

...
require('./importantUtilities.js');
...

// File: /root/apps/app1.js:

...
require('../importantUtilities.js');
...

There is no need to prepend __dirname, and I don't see how require functions without this piece of information.

How can require be implemented to return the same file for different file descriptors?

EDIT: The fact that the following example works also blows my mind (using the same file structure):

// File: /root/main.js:

...
module.exports.getUtilities = function() { return require('./importantUtilities.js'); };
var utilities = module.exports.getUtilities(); // Works fine
...

// File: /root/apps/app1.js:

...
var main = require('../main.js');
var utilities = main.getUtilities(); // Works fine
...

It seems that require is not even determining the base path from the calling scope; it's more so that somehow every occurrence of require in the source code is bound with the source code's filepath information. Is this correct?

How does any of this work??


Solution

  • every occurrence of require in the source code is bound with the source code's filepath information

    Yes, that's exactly correct. More precise, according to docs:

    require(X) from module at path Y

    1. If X begins with './' or '/' or '../'

      a. LOAD_AS_FILE(Y + X)

    i.e. it concatenates current file's path with the path being required.