How NodeJS Require works!

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.

  1. Why use “require”
  2. Example of require function
  3. module.load & module.compile
  4. Flow of require
  5. Order of require function looking for files

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 builtin 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.

Example:

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

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:

{
  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.

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.

The first step resolution is an enclosed step wherever node.js calculates the file methods etc. in the second step that is loading, 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 caches it.

So, primarily node is never aware of what symbols a commonJS 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.

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.

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 the same way as built-in and npm-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 combine their knowledge and skills to develop and deliver web and mobile apps that boost business and increase output for our clients.

Mobile App Marketing Mistakes That Can Hurt Your Brand

2020 is going to revolutionize the world with mobile apps becoming a part of nearly all human activities. With millions of apps competing for more visibility and more downloads, you can’t afford to make these mobile app marketing mistakes and damage your brand

Read More

All About On-Demand Car Parking App Development

Among the thousands of wonders the IT industry has gifted this world, one of the most notable solutions is on-demand car parking app development. Fast-growing urbanization has made finding parking spaces a nightmare for most people

Read More

Types of apps an AngularJS development company can build for you

AngularJS has become a preferred framework for building apps. An AngularJS development company can build different types of apps for you by leveraging this framework.

Read More