Nodejs Learning: Introduction to Local Modules

Hi there, it is DAY 2 of learning Nodejs. In this article, we are going to learn how how to create a module. Let's get right into it.

  1. In the desktop create a folder module.

  2. Inside the module folder create a file app.js

  3. Still on the same module folder create user.js. This is the file we are going to be creating our module.

  4. Lets begin with user.js. Open it in editor of your choice. ie vscode.

  5. Lets declare the firstname and lastnameof the user.

const firstname="boratechlife";
const lastname = "kiprono";

6.Now lets define a function to display the occupation of the user.

function getOccupation() {
return "I freelance web Developer on Fiverr"
}

7.Now export firstname and lastname

module.exports.firstname=firstname
module.exports.lastname= lastname

8.Now lets go to app.js and import our user module

const user = require('./user');

9.Lets now get the firstname, lastname, and getOccupation()

console.log(user.firstname)
console.log(user.lastname)
console.log(user.getOccupation())

10.Now run your app by executing node app.js in the terminal. Make sure you open the terminal in the modules Folder