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.
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. - 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.exports
the object out of that file. The module’s exported methods and attributes will be loaded into the variable to which you assign therequire
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
callsrequire(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 loadX
as a file or a directory within the specified path relative toY
. - Node.js searches the
node_modules
folder of the current directory forX
if it is not a core module and does not begin with a relative path. Thenode_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 itsmain
field. It searches that directory forindex.js
if 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.exports
when another filerequire
s 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.exports
exposes the entire object it points to, whileexports
(as a property ofmodule.exports
) exposes each property. Sincemodule.exports
still points to the original, empty object, any previous assignments toexports.property
will no longer work if you reassign it. To avoid confusion, keep tomodule.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.