Page Content

Tutorials

What is the Node.js Modules Concept?

Node.js Modules Concept

Developing apps with Node.js require organising code into reusable and controllable components using the Module System. It is mostly based on the exports object and the require keyword.

Related code is contained in a single unit, usually a single JavaScript file, by a module. For handling the complexity of larger applications, this strategy is essential. Your code will be simpler to test, maintain, and update if you divide your program into discrete modules. This will allow you to build loosely linked applications that scale effectively. The CommonJS specification is the foundation of the module system for Node.js. Basically, any Node.js file or group of files can be used as a module if its data and functionalities are made available to other programs.

The Keyword

The require method is the main way Node.js loads modules. Use it wherever in your Node.js scripts because it’s a global variable.

The require function can be used to load:

  1. Built-in Node.js core modules: These modules come bundled with Node.js and provide essential functionalities for tasks such as working with the file system (fs), making HTTP requests (http), or interacting with the operating system (os). You do not need to install these separately.
  2. Your own local files:
  3. As your application grows, you’ll want to organise your code across multiple files. require allows you to load these custom JavaScript files by providing a relative path to the file you wish to import. The path typically starts with ./ for files in the current directory or ../ for parent directories. You can often omit the .js extension.
  4. Third-party npm modules: Node Package Manager (npm) is the default package manager for Node.js, providing access to a vast ecosystem libraries. After installing an npm package (e.g., npm install express), you can import it by simply specifying its name.

How require works

  • Evaluation and Return Value: Node.js evaluates the code described in the designated module and returns the module when require() is module.exports the object out of that file. The module’s exported methods and attributes will be loaded into the variable to which you assign the require call.
  • Blocking Operation: One of the synchronous (blocking) operations is require(). This indicates that until the necessary module is fully loaded, your current script will not run. Generally speaking, modules only need to be loaded once, therefore this is okay.
  • Caching: Node.js caches modules when they are loaded for the first time in order to maximise performance. In order to prevent the code of the module from being performed again, require need calls to the same module will return the same cached instance. As a result, file reads are decreased and program execution is accelerated.
  • Module Resolution Order: When module Y calls require(X), Node.js locates the module in a particular order:
    • If X is a core module, it returns the core module.
    • If X begins with ./, /, or ../, it attempts to load X as a file or a directory within the specified path relative to Y.
    • Node.js searches the node_modules folder of the current directory for X if it is not a core module and does not begin with a relative path. The node_modules folders in parent directories up to the file system root are searched recursively if nothing is found.
    • Node.js first searches for a package.json file in a specified folder (e.g., require('./myModuleDir')) and uses its main field. It searches that directory for index.js if there is no main field or package.json.

The Object

The exports object and module.exports are key to making functionality from your module files accessible to other modules that require them. Everything defined inside a module is private by default and does not pollute the global scope, unless it is explicitly assigned to module.exports.

There are two main approaches to provide functionality:

  1. Assigning to module.exports: A single function, class, or literal object can be exported using this method. This module’s return value will match module.exports when another file requires it.
  2. Adding properties to exports: To add properties to exports, use the exports object, which is a shortcut to module.exports. You can attach multiple properties (functions, variables, objects) to exports, allowing them to be used as separate members when the module is needed.
  3. Key Distinction: module.exports exposes the entire object it points to, while exports (as a property of module.exports) exposes each property. Since module.exports still points to the original, empty object, any previous assignments to exports.property will no longer work if you reassign it. To avoid confusion, keep to module.exports when exporting a single major functionality.

In conclusion

It is essential to comprehend the require and exports process in order to properly structure your Node.js applications. This will enable you to utilise the extensive library that npm provides and construct intricate systems from smaller, reusable components.

Index