DEV Community

Ahmd Talat
Ahmd Talat

Posted on • Edited on

6

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.

Neon image

Serverless Postgres in 300ms (❗️)

10 free databases with autoscaling, scale-to-zero, and read replicas. Start building without infrastructure headaches. No credit card needed.

Try for Free →

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay