DEV Community

Ahmd Talat
Ahmd Talat

Posted on • Updated on

Node.js and the require function


const hello = require('./hello.js')

I've always been curious about how things work behind the scenes, and today I'd like to share with you how the require function works in Node.js.

But, what is a module in Node.js?

a reusable block of code whose existence does not accidentally impact other code.

require actually does three main things:

  1. locates where the file is.
  2. wraps the content of the file in a function and executes it.
  3. return the module.exports

That's it :)
let's see how every step works

File Location

First, Node.js checks if that file is a built-in module by calling this function:

Module._resolveLookupPaths = function(request, parent)

and if it's not the resolveLookupPaths return the path to the parent directory. If the string passed is a directory, Node looks for an index.js file. Then it creates a new object

const module = new Module(filename, parent);

, finally, the module gets cached, for more info require.cache .

Wrapping the content

In the next 2 steps, the file's content is loaded and passed to a compile function to get executed.

const content = fs.readFileSync(filename, 'utf8');

module._compile(stripBOM(content), filename);

The code of hello.js is wrapped inside this function


function(exports, require, module, __filename, __dirname) { 
  function Hello() {
    console.log("hello from emitter");
  }
  console.log("hello from hello.js");
  module.expors = Hello;
}

Enter fullscreen mode Exit fullscreen mode

and this wrapper function is invoked by the call method.

result = compiledWrapper.call(thisValue, exports, require, module,
filename, dirname);

the content gets executed hello.js

finally

this.exports is returned

return this.exports;

, which in our case will be

function Hello() {
console.log("hello from emitter");
}

Actually, there is much much more, but I tried to mention the most important aspects of it.
Thanks, your feedback is highly appreciated.

Top comments (0)