Node.js | Local Module

Node.js comes with different predefined modules (e.g. http, fs, path, etc.) that we use and scale our project. We can define modules locally as Local Module. It consists different functions declared inside a JavaScript object and we reuse them according to the requirement. We can also package it and distribute it using NPM.

Defining local module: Local module must be written in a separate JavaScript file. In the separate file, we can declare a JavaScript object with different properties and methods.

Step 1: Creating a local module with filename Welcome.js



filter_none

edit
close

play_arrow

link
brightness_4
code

const welcome = {
  
    sayHello : function() {
        console.log("Hello GeekforGeeks user");
  },
  
  currTime : new Date().toLocaleDateString(),
  
  companyName : "GeekforGeeks"
}
  
module.exports = welcome

chevron_right


Explanation: Here, we declared an object ‘welcome’ with a function sayHello and two variables currTime and companyName. We use the module.export to make the object available globally.

Part 2: In this part, use the above module in app.js file.

filter_none

edit
close

play_arrow

link
brightness_4
code

var local = require("./Welcome.js");
local.sayHello();
console.log(local.currTime);
console.log(local.companyName);

chevron_right


Explanation: Here, we import our local module ‘sayHello’ in a variable ‘local’ and consume the function and variables of the created modules.
Output:

Hello GeekforGeeks user
12/6/2019
GeekforGeeks


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.