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:
- 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. - Your own local files:
- As your application grows, you’ll want to organise your code across multiple files.
requireallows 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.jsextension. - 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()ismodule.exportsthe object out of that file. The module’s exported methods and attributes will be loaded into the variable to which you assign therequirecall. - 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,
requireneed 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
Ycallsrequire(X), Node.js locates the module in a particular order:- If
Xis a core module, it returns the core module. - If
Xbegins with./,/, or../, it attempts to loadXas a file or a directory within the specified path relative toY. - Node.js searches the
node_modulesfolder of the current directory forXif it is not a core module and does not begin with a relative path. Thenode_modulesfolders in parent directories up to the file system root are searched recursively if nothing is found. - Node.js first searches for a
package.jsonfile in a specified folder (e.g.,require('./myModuleDir')) and uses itsmainfield. It searches that directory forindex.jsif there is no main field orpackage.json.
- If
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:
- Assigning to
module.exports: A single function, class, or literal object can be exported using this method. This module’s return value will matchmodule.exportswhen another filerequires it. - Adding properties to
exports: To add properties toexports, use the exports object, which is a shortcut tomodule.exports. You can attach multiple properties (functions, variables, objects) toexports, allowing them to be used as separate members when the module is needed. - Key Distinction:
module.exportsexposes the entire object it points to, whileexports(as a property ofmodule.exports) exposes each property. Sincemodule.exportsstill points to the original, empty object, any previous assignments toexports.propertywill no longer work if you reassign it. To avoid confusion, keep tomodule.exportswhen 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.
