How does the require() function work in Node.js?

By Gulshan Saini
Published in NodeJS
January 03, 2023
1 min read

In Node.js, the require() function is used to include modules that exist in separate files. When you call require() with the name of a module, it returns an object representing the module.

The basic functionality of require() can be thought of as follows:

  1. If the specified module is a core module (e.g. fs, http, etc.), the module is returned.
  2. If the specified module is not a core module, require() will look for the module in the following places:
  • A folder with the same name as the module
  • A node_modules folder
  • Up the directory tree, repeating step 2 until the module is found or the root directory is reached

Once the module is found, require() will:

  1. Check if the module is already in the require.cache object. If it is, the cached version of the module will be returned.
  2. If the module is not in the cache, require() will:
  • Load the module’s code
  • Wraps the code in a function, to provide local scope for the module
  • Calls the function, passing in exports, module, and require objects as arguments
  • Stores the exports object in the require.cache object
  • Returns the exports object

Example 1

Here’s an example of how you might use require() in a Node.js script:

const fs = require('fs');

fs.readFile('/path/to/file', (err, data) => {
  if (err) throw err;

In this example, the fs module is included and used to read a file.

Example 2

Here’s another example, suppose you have a file called math.js that contains some math functions:

// math.js

exports.add = (a, b) => {
  return a + b;

exports.subtract = (a, b) => {
  return a - b;

You can include and use the functions in math.js in another file like this:

// main.js

const math = require('./math');

console.log(math.add(1, 2));  // 3
console.log(math.subtract(5, 3));  // 2

The require() function will look for the math.js file in the same directory as main.js, load the code in the file, and return an object with the functions specified using the exports object. In this case, the returned object has the add and subtract functions, which can be called as shown in the example.

require() can also be used to include built-in Node.js modules and third-party modules installed in the node_modules directory. For example, to include the fs module, which provides functions for interacting with the file system, you can use:

const fs = require('fs');


Previous Article
React hooks explained with examples

Related Posts

Understanding the Event Loop: How Node.js Executes Asynchronous Callbacks
January 04, 2023
5 min
Gulshan Saini

Gulshan Saini

Fullstack Developer



Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media