Node.Js with Livia || Node.Js Modules: A Beginner's Guide to Building, Using, and Sharing Code Blocks

Node.Js with Livia || Node.Js Modules: A Beginner's Guide to Building, Using, and Sharing Code Blocks

Hey there 👋 this is the second blog post for the series NodeJs with Livia. I am really excited about this one because I would be walking you through the most important component of node.Js, most of the time you will be needing one or two modules to create a node.Js project.

Modules 🥳

A module is a collection of related functions/classes that provides some kinds of services. In simple terms, a module is a piece of reusable code.

In Javascript modules could be a .js file or a directory containing .js files. Modules help developers adhere to the DRY (Don't Repeat Yourself) principle in programming. They also help to break down complex logic into small, simple, and manageable chunks. Before these modules can be used in other files their content needs to be exported.

Why is it so important to adopt modules? 🙄

  • Reusability: a block of code can be used multiple times.

  • Easy and Faster Fixes: It’s easier to locate and fix faults.

  • Code is easier to test

  • Code is easier to read

Types of Node.Js Modules

There are three major node.Js modules which are:

  • Core/Built-in modules

  • Local modules

  • Third party modules

Core/Built-In Modules

These modules come with Node.js installation. They’re basically built-in the platform. These modules can be imported using the require function.

require() is a built in function in node.Js use to include modules that exists in a separate file.

const variableName = require(‘ moduleName’)

The following is a list of some important core modules in Node.js:

Core Modules

Description

http

creates an HTTP server in Node.js.

assert

set of assertion functions useful for testing.

fs

used to handle file system.

path

includes methods to deal with file paths.

process

provides information and control about the current Node.js process.

os

provides information about the operating system.

querystring

utility used for parsing and formatting URL query strings.

url

module provides utilities for URL resolution and parsing

Taking an example using the http module:

const http = require('http') 

server = http.createServer((req, res) => { 
    res.writeHead(200, {'Content-Type': 'text/plain'}) 
    res.end('HTTP Modules')
})

server.listen(3000)

Local Modules

These are modules we build ourselves. When you work with Node.js, you create local modules that you import and use in your program. Let's see how to do that;

Let’s create a simple Greeting module:

  • Create two .js files index.js and greetings.js

  • In the greetings.js file we will create a greet function that will take in two parameters usersName and timeOfDay

function greet(userName, timeOfDay){
    console.log(`Good ${timeOfDay}, ${usersName})
}

module.exports = greet;

module.exports = greet; makes the function greet accessible outside the greetings.js file

  • In the index.js file we can simply import the greetings.js file using the require function:

const greet = require(‘./greetings.js’);

const greet = require(‘./greetings.js’);

greet(“Olivia”,”Afternoon”);

Third-Party Modules

One good thing about using modules in Node.Js is that people can get to use your modules when they are made public online, basically you are sharing your modules with others.

Before these modules are used or imported they have to be installed. The Node Package Manager (NPM) makes that possible. When you install Node.js, NPM comes along with it.

With NPM, you can share your modules as packages via the NPM registry. And you can also use packages others have shared.

Examples of third party modules are: express, cors, bcrypt, body-parser, nodemon, dotenv and so on

How to use third-party modules

  • Initalize npm, in your terminal or command line write:

    npm init -y

    A package.json file would automatically be created. This file stores the names and versions of all the dependencies used for a project.

  • Install the module, in your terminal or command line write

    npm install <module name>

    There are different ways of installing third party modules, they can be installed globally or in just a project directory. The above syntax is for installing in a project directory.

    Syntax for global installation:

    npm install -g <module name>

    • Let’s use the express module, Installing the express module:

      npm install express

  • Once the module is installed the next thing to do is import the module

    const express = require(‘express’);

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`
)};

If you got this far Well-done, you can reference this Github repo for the codes samples.

I would also like to know your thoughts on packages, modules and libraries. Do not hesitate to share your thoughts in the comment section.

Thank you for reading 😊