Getting Started With Node Modules I
Understanding modules in JavaScript
Table of contents
Hello there ๐, This is the second article in the Node.js series.
In this article, we will be diving deeper into the node modules we have.
NB: If you are new to this series, here is a link to the previous article, Introduction to Node.js
What is a Module?
A module is a block of code that is contained and interacts with external applications based on shared functionality.
NB: A module can be a single file or a collection of files and folders. It can also be seen as a section of program functionality.
There are three types of modules in any of our applications:
- Core modules
- Local modules
- Third-party modules
Core Modules
These are in-built modules that come with the Node.js application. These modules don't need to be installed as they are "follow-come". The Node core modules can be seen here. Some common examples are the Events, HTTP, File system, OS etc.
To use any of these models, we either import them by using the import
command:
import varName from "moduleName";
// or
import { varName } from "moduleName";
or use the require
keyword:
const varName = require('moduleName');
NB: When using the
require
keyword, it is advisable that theconst
for declaring that variable. This is because, we do not want to redeclare that variable again, thereby changing its meaning
Local Modules
These are files within our development environment. The modules are written by the developer, but needed in another file or module within the development environment. Let's say our files are arranged in this order
If we need a particular functionality from the app.js file inside the index.js file which is inside the same folder "HASHNODE PROJECT", here is how we import it using the require
keyword and our relative URL
const app = require('./app.js')
If we require this same functionality in the user.js
file which is in the "model" folder,
const app = require('../app.js');
Third-Party Modules
These are modules that have been written by other developers, but you need them in your code. Node.js has a package manager for getting these modules and packages. This packager is called the Node Package Manager (NPM) and is the most popular. There are other package managers, for example :
To use the NPM to install a module,
npm install express
// or
npm i expresss
After installing it, we can now require the module in any file we need it.
In the next article, I'll be talking about the NPM, so stay tuned.
Thanks for reading. ๐๐
I encourage you to subscribe to my newsletter to get an update when a new article drops.
You can also follow me on these platforms:
Twitter ๐ฆ: @nwokporo_ebuka
LinkedIn โก: @chukwuebuka_nwokporo
GitHub ๐: @ebukvick
Hashnode ๐: @codedaddy