Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Django

    Building Rest API With Django Using Django Rest Framework and Django Rest Auth

    JavaScript

    React Lesson 1: Introduction to React

    Java

    10 Practices You Should Avoid to Become a Good Java Developer

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Wednesday, September 10
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / JavaScript / Node.js / Node.js Lessons / Node.js Lesson 2: Modules and Exports
    Beginners

    Node.js Lesson 2: Modules and Exports

    Mohammad Shad MirzaBy Mohammad Shad MirzaSeptember 7, 2020No Comments7 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Node.js Lesson 2: Modules and Exports
    Node.js Lesson 2: Modules and Exports
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    Node.js Lesson 2: Modules and Exports
    Node.js Lesson 2: Modules and Exports

    Hey everyone, we learned what are modules and how to create one in the previous lesson. This lesson will dive deeper with the module, understand what properties it carries, and then talk about export in detail. Let’s start.

    Properties of Module

    Every javascript file in the Nodejs project is a separate module and it contains a global module object. Let’s try to log in and see what’s inside. Go to index.js and add this code:

    console.log(module);

    This will log the information about the module. Let us understand it’s properties briefly:

    • filename – full name of the file
    • id – generally contains a detailed path to the file. If an operation/file system supports symbol links, it means all symbol links will be drawn.
    • exports – all information that goes externally. We talked about it at our last lesson.
    • parent – a link to a parent module, i.e. the module that required this one.
    • loaded – shows whether a module has been uploaded. When the module gets moved to a console, it hasn’t been processed yet.
    • children – the modules that were connected by this module via require.
    • path – a sort of an inner ID.

    Using these properties, the module keeps track of itself. These all properties have their relevant importance but right now we are interested in two parameters: parent and exports. Let us talk about these.

    Parent Property and How to use it

    A file in Nodejs can be run directly by calling node filename.js or it can just work as a module that exports a certain function to another.

    We can use module.parent to check in which mode our file is running. module.parent === true means that a parent is calling this file using require(‘./filename.js) and if it is false then it is run directly by node filename.js

    Using this check, we can tell the program to do two different things depending on how the code is executed. In the example below, we will export the function run() if it is working as a module and being called in a parent file. Otherwise, we will simply run the function.

    var user = require('./user');  
      
    function run() {  
        var tim = new user.User("Tim");  
        var tom = new user.User("Tom");  
      
        tim.hello(tom);  
    }  
      
    if (module.parent) {
        // used with require(./user);
        exports.run = run;  
    } else {
        // ran with node user.js
        run();  
    }

    If there isn’t a parent module, we can run this file independently using this feature. Now let’s talk about exports.

    Exports and How to use it

    When you’re building a Nodejs application, you will have to create a lot of modules that will become building blocks of your application. You need to understand how to export them and use them wherever required.

    Read More:  Progressive Web Applications and Service Workers

    module.exports is an object that the current module returns when it is “required” in another program or module. Whenever we want something like values or functions to be available for another module to import and use, we attach that value or function with this module.exports

    Example:

    Export a few properties from one module:

    // ./moduleOne.js
    const firstName = "Shad";
    const lastName = "Mirza";
    
    function getFullName (){
        return firstName + lastName;
    }
    
    module.exports.firstName = firstName;
    module.exports.lastName = lastName;
    module.exports.getFullName = getFullName;

    Require and use it in another module:

    // ./moduleTwo.js
    const name = require('./moduleOne');
    
    console.log(name.firstName);
    console.log(name.lastName);
    console.log(name.getFullName);

    We can use variables and methods of one module into another in a similar fashion.

    We can also use exports instead of module.exports and achieve the same functionality. You can consider this as a shorthand of the longer method. Example, this will totally work fine:

    // ./moduleOne.js
    const firstName = "Shad";
    const lastName = "Mirza";
    
    function getFullName (){
        return firstName + lastName;
    }
    
    exports.firstName = firstName;
    exports.lastName = lastName;
    exports.getFullName = getFullName;

    Whereas, if you assign the properties directly to exports, it won’t’s work:

    exports = firstName;

    This happens because exports are an object and we assign properties to it. These properties then get exported to another module. By assigning directly to exports itself, we reinitialized that property which will break the desired functionality.

    exports can be considered as an alias of module.exports to write less code. Imagine it as something like this:

    exports = module.exports = {}

    Note: Please note that we are actually returning module.exports not exports.

    Our next stage will be to add a database to the project.

    Connect to Database

    Let’s create a db directory and move our JSON file into it. Add a file index.js which will be a helper module to connect with db (en.json) and get phrases from the JSON file.

    // ./db/index.js
    
    var phrases;
    exports.connect = function() {
        phrases = require('./en');
    };
    
    exports.getPhrase = function(name) {
        if (!phrases[name]) {
            throw new Error("There is no such a phrase: " + name);
        }
        return phrases[name];
    };

    We just created a db module that has a connect() method to connect with the database and getPhrase method to fetch data. This method will return a respective phrase, but if not – it will show an error.

    Now, let’s use this module in user/index.js

    var db = require('./db');
    
    function User(name){
        this.name = name;
    }
    
    User.prototype.hello = function(who){
        console.log(db.getPhrase("Hello") + ", " + who.name);
    };
    
    console.log("user is required!");
    
    module.exports = User;

    We just replaced requiring en.json with db.js and then logging phrase using db.getPhrase method.

    Read More:  Web Accessibility: Standards, Guidelines, Testing & Evaluation Tools

    This won’t work unless we connect with the database first. Go to index.js:

    var db = require('../db');
    db.connect();
    
    var User = require('./user');
    
    function run() {
        var tom = new User("Tom");
        var tim = new User("Tim");
    
        tom.hello(tim);
    
        console.log(db.getPhrase("Run successful"));
    }
    
    if (module.parent) {
        exports.run = run;
    } else {
        run();
    }

    The first time a module is executed, it gets initialized. This is when we call connect() to connect to the database (JSON file in our case). After that, we can use anything from the database as we want.

    We are using index.js to connect to our database. This looks like a task of a server. Let’s move the whole logic inside a file server.js and then import it in the root index.js as follows:

    var server = require('./server');
    
    server.run();

    We have successfully connected with the database using Module ✨. Now, let’s talk about how modules are searched and what it has to do with Module Caching.

    Module Caching

    All the modules get instantiated with some null properties when required. Ours connect function is instantiating phrases with en.json instead of null.

    What do you think will happen if we require db again?

    You might think it will initialize the object again but that is not what happens. Requiring the same module in a different location doesn’t create different instances but use the one that was initialized the first time. This is what we call Module Caching.

    The module gets cached during the first require statement, meaning only one instance of that object is created — subsequent require statements in other modules just enable us to access that same object.

    It means that the changes with the db object will persist upon us trying to import db inside the server and then in the user module. We are using the same db object in both server.js and then in user/index.js

    What we learned

    In this lesson, we learned

    1. About the properties of the Module object
    2. What is Parent property and how to use it
    3. What is Exports
    4. How to export functionalities and use it in another module
    5. How to connect to the database (JSON file)
    6. What is Module Caching

    That’s it for now, we will talk more about modules as we progress with the development. Our next lesson will be about the Node Package Manager (NPM).

    Check out the source code of this lesson in this GitHub repo.

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Mohammad Shad Mirza
    • X (Twitter)
    • LinkedIn

    JavaScript lover working on React Native and committed to simplifying code for beginners. Apart from coding and blogging, I like spending my time sketching or writing with a cup of tea.

    Related Posts

    Mastering REST APIs: Essential Techniques for Programmers

    December 18, 2024

    Crafting Interactive User Interfaces Using JavaScript Techniques

    December 17, 2024

    Effective Strategies for Utilizing Frameworks in Web Development

    December 16, 2024

    Comments are closed.

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss
    JavaScript February 14, 2019

    AI in Recruitment: Cases and Trends

    AI + HR: this combination helps companies lower the time they spend on sorting candidates and improve employee retention. Let’s examine what exactly they’re doing to make their recruitment strategies effective:

    Express.js Lessons. Logger, Configuration, Templating with EJS. Part 2.

    December 2, 2016

    Startup Spotlight: Five Companies That Revolutionize Healthcare & Wellness

    March 12, 2019

    How to Run API Tests Automatically Every Time Your App Is Deployed using Loadmill

    September 25, 2020

    Categories

    • AI & Automation
    • Angular
    • ASP.NET
    • AWS
    • B2B Leads
    • Beginners
    • Blogs
    • Business Growth
    • Case Studies
    • Comics
    • Consultation
    • Content & Leadership
    • CSS
    • Development
    • Django
    • E-commerce & Retail
    • Entrepreneurs
    • Entrepreneurship
    • Events
    • Express.js
    • Facebook Ads
    • Finance & Fintech
    • Flask
    • Flutter
    • Franchising
    • Funnel Strategy
    • Git
    • GraphQL
    • Home Services Marketing
    • Influencer & Community
    • Interview
    • Java
    • Java Spring
    • JavaScript
    • Job
    • Laravel
    • Lead Generation
    • Legal & Compliance
    • LinkedIn
    • Machine Learning
    • Marketing Trends
    • Medical Marketing
    • MSP Lead Generation
    • MSP Marketing
    • NestJS
    • Next.js
    • Node.js
    • Node.js Lessons
    • Paid Advertising
    • PHP
    • Podcasts
    • POS Tutorial
    • Programming
    • Programming
    • Python
    • React
    • React Lessons
    • React Native
    • React Native Lessons
    • Recruitment
    • Remote Job
    • SaaS & Tech
    • SEO & Analytics
    • Soshace
    • Startups
    • Swarm Intelligence
    • Tips
    • Trends
    • Vue
    • Wiki
    • WordPress
    Top Posts

    HR Tech Conferences Worth Your Time [2019]

    Events August 8, 2019

    If Trello became too small for you.

    JavaScript September 30, 2016

    Express.js Lessons. Express: Basics and Middleware. Part 2.

    Programming November 24, 2016

    Strategic Methods for Building a LinkedIn Prospect List

    LinkedIn December 10, 2024

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    About Us
    About Us

    Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

    7901 4th St N, Suite 28690
    Saint Petersburg, FL 33702-4305
    Phone: 1(877)SOSHACE

    Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
    Our Picks
    JavaScript

    JavaScript Design Patterns in Action

    JavaScript

    Nest.js and AWS Lambda for Serverless Microservices

    Recruitment

    Crafting Compelling Job Descriptions for Successful Recruitment

    Most Popular

    Getting started with Next.js

    JavaScript

    Consulting Project Prepare for a new job

    Consultation

    Introduction to Micro Frontends: The New Tech on the Block

    JavaScript
    © 2025 Soshace Digital.
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.