Ankaj Gupta
December 30, 2018

Require module in Node.js | Nodejs

Understanding require() in Node.js

The require() function allows you to include modules into your programs. You can import built-in Node.js modules, community-based modules (node_modules), and local modules.

How require() Works

The require() function returns an object, which references the value of module.exports for a given file. When invoked, it performs a sequence of tasks.

Important: require is a function that takes one argument called path in Node.js.

Module Resolution Order

The require() function searches for modules in the following order:

1. Built-in Node.js Modules

Core modules like fs, path, crypto, etc.

2. Modules in node_modules Folder

Community-installed packages like Express, Lodash, etc.

3. Local Modules (with Paths)

If the module name contains ./, /, or ../, it looks for the directory in the given path. Matches extensions: *.js, *.json, and *.node.

How to Use require() Function

Importing a Local Custom Module

Import modules from your project using relative or absolute paths:

const myLocalModule = require('./path/myLocalModules');

Importing a JSON File

Directly require JSON files to get parsed data:

const jsonData = require('./path/jsonFile.json');

Importing Built-in or npm Modules

Import Node.js built-in modules or packages from node_modules:

const crypto = require('crypto');        // Built-in
const express = require('express');      // From node_modules

Complete Example

Example demonstrating how to use the fs module to read a file:

const fs = require('fs');

fs.readFile('./myfile.txt', 'utf-8', (err, data) => {
    if(err) {
        throw err;
    }
    console.log('data: ', data);
});

Explanation: In this example, the path is ./myfile.txt. The require('fs') loads Node.js's built-in file system module.

Common require() Patterns

Path Prefixes

  • ./ - Current directory
  • ../ - Parent directory
  • / - Absolute path
  • No prefix - node_modules

File Extensions

  • .js - JavaScript files
  • .json - JSON files
  • .node - Compiled addons
  • Extensions optional for .js

Types of Modules

Module Type Example Use Case
Built-in require('fs') Core Node.js functionality
Local require('./myModule') Project-specific code
Third-party require('express') Community packages
JSON require('./config.json') Configuration data

Key Points

  • Module Caching: Modules are cached after the first require. Subsequent calls return the cached version
  • Circular Dependencies: Be careful with circular dependencies as they can cause unexpected behavior
  • Sync Operation: require() is synchronous and blocks execution until the module is loaded
  • module.exports: Use module.exports to export functionality from your modules

Summary

The require() function is fundamental to Node.js module system, allowing you to load built-in modules, third-party packages, local files, and JSON configurations seamlessly.

Understanding how require() resolves modules helps you write better organized, modular Node.js applications. Remember that module resolution follows a specific order, and files are cached after the first require.

Node.js

Join the discussion

Comments

0 comments

No comments yet — be the first to share your thoughts.

Related Posts