Node.js Module System and require Function
Md Pervez Hossain
Posted on October 15, 2024
Global Objects in Node.js vs Browsers
- In browsers, the global object is window.
- In Node.js, the global object is global.
- However, this in the global scope of a Node.js module points to module.exports, not global.
- this keyword is an empty object ({}) in node js
Entry Point: Every Node.js project has a main file (e.g., index.js or app.js) that starts the application, setting up the environment and logic.
Node.js Modules Overview
In Node.js, modules help organize and encapsulate code. A module is simply a file containing JavaScript code that can be imported or exported using CommonJS or ESM systems.
- Files as Modules: Each file in Node.js is a module with its own scope.
Types of Modules:
- Core Modules: Built-in, no installation needed (const fs = require('fs');).
- Third-Party Modules: Installed via npm (const express = require('express');).
- Local Modules: Use relative paths (const myModule = require('./myModule');).
Modules Key Points:
- Every file is a module.
- require() Function: Used to import modules, loaded synchronously.
- module.exports: Used to export functionality from a module.
- Core and third-party modules don't need paths, but local modules do.
- Modules protect their variables,functions,objects,and arrays from leaking by default unless exported.
- variables,functions,objects,and arrays etc are scoped to their local module
- When you export more than one, you need to wrap it into an object
- In Node.js, this in the global scope refers to an empty object, while this inside a module refers to module.exports.
In JavaScript, a module is simply a file that contains code you want to use in other parts of your program. Modules help organize and encapsulate functionality, making your code more maintainable, reusable, and easier to manage .
There Two types of Module :
- Common Js Module π
- Es Module π
Common Js Module π
CommonJS is a module system used in Node.js to allow modular code by defining how to import and export modules.
- Uses require() to import and module.exports to export.
- Synchronous loading of modules.
- Works in non-strict mode. ( Example: You can declare variables without var, let, or const, but itβs bad practice.)
- IIFE (Immediately Invoked Function Expression) wraps modules for local scope.
- Still widely used in Node.js, though ESM is preferred for new projects.
CommonJS allows you to break your code into reusable modules, making it more organized and maintainable.
default module system in older Node.js versions.
Useful built-in global variables available in every CommonJS module:
- module.exports: To define what a module exposes.
- require(): To load another module.
- __dirname: The directory path of the current module.
- __filename: The absolute path of the current module file.
Es Module π
ESM (ECMAScript Modules): This is the standard JavaScript module system, also referred to as ES Modules or MJS (for files with .mjs extension).
- Uses import and export for modular code.
- Standard in frameworks like React, Vue, and Angular.
- Module loading is async, enabling better performance.
- ESM enforces strict mode by default.
- Must use var, let, or const for variable declarations.
- Files use .mjs or "type": "module" in package.json for Node.js.
- ESM supports await at the top level without needing to wrap it in an async function.
- ESM uses import instead of require().
- Supports named exports and default exports for flexibility.
- Once exported, values cannot be re-assigned by the importer.
Differences between CommonJS and ESM
CommonJS is synchronous and can be used in Node.js without any configuration.
ESM is the standard in modern JavaScript and works both in the browser and in Node.js with a few extra steps (like setting "type": "module" in package.json or using the .mjs file extension).
Conclusion
- Module: A reusable block of code (functions, variables, etc.) in a file.
- Module System: The system used to manage, load, and export/import these modules.
- Node.js: Primarily used the CommonJS module system, but now also supports ESM.
- Benefits: Makes code modular, maintainable, and reusable across large applications.
- In Node.js, module.exports is a special object that is used to export values (such as functions, objects, or variables) from a module, so that they can be imported and used in other files (modules).
- When you write code in Node.js, each file is treated as a separate module. The module.exports object is what defines the public API of that module β meaning whatever you assign to module.exports will be accessible when you require() that module in another file.
Node.js require() Function Jobs :
- Resolving the Module β Identifies the location of the module (file path, core module, or node_modules).
- Loading the Module β Reads the content based on its file type.
- Wrapping in IIFE β Encapsulates the module in a function to provide local scope and access to necessary variables.
- Code Evaluation β Executes the module's code and returns the module.exports object.
- Caching β Stores the module in memory for future require() calls to reuse.
"Node.js does not directly send module code to the V8 engine. Instead, it first takes the module content, wraps it inside an IIFE (Immediately Invoked Function Expression), and then sends this wrapped code to the V8 engine for execution."
Breakdown:
Module Wrapping: Node.js wraps the code of each module in a function (IIFE) to create a private scope and inject variables like exports, require, module, etc.
Execution in V8: After wrapping the module in an IIFE, Node.js sends the wrapped function to the V8 JavaScript engine, where it is parsed and executed.
What is IIFE in JavaScript β
- IIFE stands for Immediately Invoked Function Expression. It's a JavaScript function that runs as soon as it is defined.
- An IIFE is created by wrapping a function inside parentheses and This parentheses convert it from a function declaration into a function expression.
- Immediately invoking it with another set of parentheses.
Why Do We Use IIFE β
- Avoid Global Variable Pollution : IIFEs create a local scope, preventing variables from affecting the global scope, avoid naming conflicts and enhancing modularity.
- Encapsulation of Code : IIFEs keep the code self-contained and inaccessible from outside, ensuring a cleaner codebase.
- Private Variables : Variables inside an IIFE are private and can't be accessed externally, improving data security.
- Initialization Code : IIFEs are ideal for executing code immediately, especially for one-time setups or initializations .
In Node.js, the module system is essential for organizing and encapsulating code. Node.js originally used the CommonJS module system with require() for importing and module.exports for exporting, making code reusable across different files. Now, with the rise of ES Modules (ESM), JavaScript has embraced a modern, standardized system using import and export with async loading and strict mode.
The primary goal of both systems is to improve maintainability, reusability, and modularity, but ESM is now favored for its performance benefits and alignment with browser-based JavaScript.
Posted on October 15, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.