Related Resources

Our Services

You May Also Like

Why Use "Require" Function And What Steps Are Involved In Loading Modules?

Krunal Shah

Dec 27, 2019

5 min readLast Updated Nov 10, 2023

Introduction

As node developers, we all know what the require() function does. But how many of us actually know how it works? We use it every day to load libraries and modules but its behavior is still a mystery for us, so let’s solve this mystery…

We will cover the below topics

Why we use “require”?

require() is used to consume modules. It allows you to include modules in your app. You can add built-in core Node.js modules, community-based modules (node_modules), and local modules too.

Node.js follows the CommonJS module system, and the built-in require function is the easiest way to include modules that exist in separate files. The basic functionality of require is that it reads a JavaScript file, executes the file, and then proceeds to return the exports object.

Hiring Nodejs Developers? Here’s Everything You Should Know

Read More

Why Use "Require" Function And What Steps Are Involved In Loading Modules?Why Use "Require" Function And What Steps Are Involved In Loading Modules?

Example:

var invisible = function () {
console.log("invisible");
}
exports.message = "Third rock techkno";

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

Why Use "Require" Function And What Steps Are Involved In Loading Modules?

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

{
  message: "Third Rock techkno",
  say: [Function]
}

If you want to set the exports object to a function or a new object, you have to use the module. exports object. So for an example:

module.exports = function () {
  console.log("hello world")
}
require('./example2.js')() //require itself and run the exports object

It is worth noting that each time you subsequently require an already-required file, the exports object is cached and reused. To illustrate this point:

node> require('./example.js')
evaluating example.js
{ message: 'hi', say: [Function] }
node> require('./example.js')
{ message: 'hi', say: [Function] }
node> require('./example.js').message = "hey" //set the message to "hey"
'hey'
node> require('./example.js') //One might think that this "reloads" the file...
{ message: 'hey', say: [Function] } //...but the message is still "hey" because of the module cache.

Why Is Node.Js So Popular?

Read More

The most important functions to check here are

  • _load
  • _compile

Module._load

This function checks whether the module is in the cache already - if so, it returns the exports object.

If the module is native, it calls the NativeModule.require() with the filename and returns the result.

Otherwise, it creates a new module for the file and saves it to the cache. Then it loads the file contents before returning its exports object.

Module._compile

The compile function runs the file contents in the correct scope or sandbox, as well as exposes helper variables like require, module, or exports to the file.

The actual loading of any module using require() happens in five steps

Why Use "Require" Function And What Steps Are Involved In Loading Modules?

The first step resolution is an enclosed step wherever node.js calculates the file methods etc. in the second step that is loading, the node pulls the code within the current method. In wrapping, phase wraps up the code within the operate as shown higher than so sends it to VM for evaluating so eventually catches it.

So, primarily node is never aware of what symWhy Use "Require" Function And What Steps Are Involved In Loading Modules?bols a common JS module goes to export till and unless the module is truly evaluated. And this is often the largest distinction with ECMAScript modules, as a result of ESM is lexical and so, the exported symbols are better known before the code is truly evaluated.

How Node JS middleware works?

Read More

The require function will look for files in the following order

  • Built-in core Node.js modules (like fs, path)
  • NPM Modules. It will look in the node_modules folder.
  • Local Modules. If the module name has a ./, / or ../, it will look for the directory/file in the given path. It matches the file extensions: *.js, *.json, *.mjs, *.cjs, *.wasm and *.node.Why Use "Require" Function And What Steps Are Involved In Loading Modules?

Built-in Modules

When you install node, it comes with many built-in modules.

Some of the most used core modules are:

fs: Allows you to manipulate (create/read/write) files and directories. path: utilities to work with files and directories paths.

NPM Modules

NPM modules are 3rd-party modules that you can use after you install them. To name a few:

lodash: a collection of utility functions for manipulating arrays, objects, and strings. request: HTTP client simpler to use than the built-in HTTP module. express HTTP server for building websites and API. Again, simpler to use than the built-in HTTP module.

Creating your own NodeJs modules

If you can’t find a built-in or 3rd-party library that does what you want, you will have to develop it yourself and import it the same way as built-in and npm-modules

TRT

We are a team of expert developers, testers and business consultants who strive to deliver nothing but the best. Planning to build a completely secure and efficient Nodejs app? 'Hire NodeJS Developers'.

Why Use "Require" Function And What Steps Are Involved In Loading Modules?

Third Rock Techkno is a leading IT services company. We are a top-ranked web, voice, and mobile app development company with over 10 years of experience. Client success forms the core of our value system.

We have expertise in the latest technologies including angular, react native, iOs, Android, and more. Third Rock Techkno has developed smart, scalable, and innovative solutions for clients across a host of industries.

Our team of dedicated developers combines their knowledge and skills to develop and deliver web and mobile apps that boost business and increase output for our clients.

Looking For Expert Guidance on Your Dream Project?

Our diverse team of industry leading veterans can help you build the most viable solution.

Schedule a free consultation call

Krunal Shah

Krunal Shah is the CTO and Co-founder at Third Rock Techkno. With extensive experience gained over a decade, Krunal helps his clients build software solutions that stand out in the industry and are lighter on the pocket.

Linkedin | Let's connect!

Projects Completed till now.

Discover how we can help your business grow.

"Third Rock Techkno's work integrates complex frameworks and features to offer everything researchers need. They are open-minded and worked smoothly with the academic subject matter."

- Dr Daniel T. Michaels, NINS