Rocket Academy Bootcamp
  • 🚀Welcome to Bootcamp!
  • 🛠️Logistics
    • Course Schedules
    • Course Methodology
    • Required Software
    • LinkedIn Education Badge
  • 📚General Reference
    • Naming, Casing, and Commenting Conventions
    • VS Code Tips
    • Recommended Resources
  • 🪨0: Foundations
    • 0.1: Command Line
    • 0.2: Git
      • 0.2.1: Branches
    • 0.3: GitHub
      • 0.3.1: Pull Requests
    • 0.4: JavaScript
      • 0.4.1: ES6
      • 0.4.2: Common Syntax
      • 0.4.3: Reference vs Value
      • 0.4.4: Classes
      • 0.4.5: Destructuring and Spread Operator
      • 0.4.6: Promises
        • 0.4.6.1: Async Await
    • 0.5: Node.js
      • 0.5.1: Node Modules
      • 0.5.2: NPM
      • 0.5.3: Nodemon
  • 🖼️1: Frontend
    • 1.1: HTML
    • 1.2: CSS
      • 1.2.1: Layout
    • 1.3: React
      • Styling in ReactJs
      • Using Styling Libraries with React
      • React Deployment
    • 1.E: Exercises
      • 1.E.1: Recipe Site
      • 1.E.2: Portfolio Page
      • 1.E.3: World Clock
      • 1.E.4: High Card
      • 1.E.5: Guess The Word
    • 1.P: Frontend App
  • 🏭2: Full Stack
    • 2.1: Internet 101
      • 2.1.1: Chrome DevTools Network Panel
      • 2.1.2: HTTP Requests and Responses
    • 2.2: Advanced React
      • 2.2.1: AJAX
      • 2.2.2: React Router
      • 2.2.3: useContext
      • 2.2.4: useReducer
      • 2.2.5: Environmental Variables
      • 2.2.6: React useMemo - useCallback
    • 2.3: Firebase
      • 2.3.1: Firebase Realtime Database
      • 2.3.2: Firebase Storage
      • 2.3.3: Firebase Authentication
      • 2.3.4: Firebase Hosting
      • 2.3.5: Firebase Techniques
    • 2.E: Exercises
      • 2.E.1: Weather App
      • 2.E.2: Instagram Chat
      • 2.E.3: Instagram Posts
      • 2.E.4: Instagram Auth
      • 2.E.5: Instagram Routes
    • 2.P: Full-Stack App (Firebase)
  • 🤖3: Backend
    • 3.1: Express.js
      • 3.1.1 : MVC
    • 3.2: SQL
      • 3.2.1: SQL 1-M Relationships
      • 3.2.2: SQL M-M Relationships
      • 3.2.3: SQL Schema Design
      • 3.2.4: Advanced SQL Concepts
      • 3.2.5: SQL - Express
      • 3.2.6: DBeaver
    • 3.3: Sequelize
      • 3.3.1: Sequelize One-To-Many (1-M) Relationships
      • 3.3.2: Sequelize Many-To-Many (M-M) Relationships
      • 3.3.3: Advanced Sequelize Concepts
      • 3.3.4 Database Design
    • 3.4: Authentication
      • 3.4.1: JWT App
    • 3.5: Application Deployment
    • 3.E: Exercises
      • 3.E.1: Bigfoot JSON
      • 3.E.2: Bigfoot SQL
      • 3.E.3: Bigfoot SQL 1-M
      • 3.E.4: Bigfoot SQL M-M
      • 3.E.5: Carousell Schema Design
      • 3.E.6: Carousell Auth
    • 3.P: Full-Stack App (Express)
  • 🏞️4: Capstone
    • 4.1: Testing
      • 4.1.1: Frontend React Testing
      • 4.1.2: Backend Expressjs Testing
    • 4.2: Continuous Integration
      • 4.2.1 Continuous Deployment (Fly.io)
      • 4.2.2: Circle Ci
    • 4.3: TypeScript
    • 4.4: Security
    • 4.5: ChatGPT for SWE
    • 4.6: Soft Skills for SWE
    • 4.P: Capstone
  • 🧮Algorithms
    • A.1: Data Structures
      • A.1.1: Arrays
        • A.1.1.1: Binary Search
        • A.1.1.2: Sliding Windows
      • A.1.2: Hash Tables
      • A.1.3: Stacks
      • A.1.4: Queues
      • A.1.5: Linked Lists
      • A.1.6: Trees
      • A.1.7: Graphs
      • A.1.8: Heaps
    • A.2: Complexity Analysis
    • A.3: Object-Oriented Programming
    • A.4: Recursion
    • A.5: Dynamic Programming
    • A.6: Bit Manipulation
    • A.7: Python
  • 💼Interview Prep
    • IP.1: Job Application Strategy
    • IP.2: Resume
    • IP.3: Portfolio
Powered by GitBook
On this page
  • Learning Objectives
  • Introduction
  • Module Scope
  • Named vs Default Exports
  • Named Exports
  • Default Exports
  • Additional Resources
  1. 0: Foundations
  2. 0.5: Node.js

0.5.1: Node Modules

Learning Objectives

  1. Node Modules define code that can be grouped together and imported from other files

  2. How to import and export functions from Node Modules

  3. We can only access imported variables and variables defined in the current module

  4. Understand the difference between named and default exports

Introduction

Node Modules (aka ES Modules) define code that can be grouped together and imported from other files. This helps clarify business logic by abstracting implementation details into separate files.

Setting up the environment:

  1. Create a new directory named npm_modules

  2. Change directory to npm_modules

  3. Run the command npm init -y to initialise an npm directory

  4. You should see a new file has been generated, the package.json

  5. To run the scripts you will need to alter this file as below:

{
  "name": "npm_modules",
  "version": "1.0.0",
  "description": "modules",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
  }
}

Alter this file by adding in a new key and value pair.

{
  "type": "module",
  "name": "npm_modules",
  "version": "1.0.0",
  "description": "modules",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
  }
}

Now you can run your scrips with node <scrip-name>

operations.js is a Node Module that exports 2 functions: add and subtract.

operations.js
export const add = (a, b) => {
  return a + b;
};

export const subtract = (a, b) => {
  return a - b;
};

index.js imports add and subtract functions from the operations module and uses them.

index.js
import { add, subtract } from "./operations.js";

console.log(add(2, 2));
console.log(subtract(2, 2));

conversion.js is a Node Module that exports functions to convert metric to US units of measurement.

conversion.js
export const kmToMiles = (numKm) => {
  // Convert KM to miles and return value in miles
};

export const celciusToFahrenheit = (tempInCelsius) => {
  // Convert Celsius to Fahrenheit and return value in Fahrenheit
};

export const kgToPounds = (numKg) => {
  // Convert KG to pounds and return value in pounds
};

index.js imports functions from conversion module and uses them without having to worry about implementation details.

index.js
import {
  kmToMiles,
  celciusToFahrenheit,
  kgToPounds,
} from "./conversion.js";

console.log(kmToMiles(3));
console.log(celciusToFahrenheit(3));
console.log(kgToPounds(3));

Module Scope

Node Modules can only access variables explicitly imported or defined in their file. For example, the variable PI in the following circleUtils module is not accessible in index.js because PI is not explicitly imported or defined in index.js.

circleUtils.js
const PI = 3.14;

export const getCircleArea = (r) => {
  return PI * (r * r);
};

export const getCirclePerimeter = (r) => {
  return 2 * PI * r;
};
index.js
import { getCircleArea } from "./circleUtils.js";

// PI is used "inside" this function
console.log(getCircleArea(2));
// But PI is not accessible as a variable unless explicitly exported and imported
console.log(PI); // Error

Named vs Default Exports

There are 2 ways of exporting variables from Node Modules: named and default.

Named Exports

Named exports allow us to export 0 or more named variables from modules. This is helpful when we want to export more than 1 function from a module.

In the circleUtils module, we export getCircleArea and getCirclePerimeter but not PI.

circleUtils.js
const PI = 3.14;

export const getCircleArea = (r) => {
  return PI * (r * r);
};

export const getCirclePerimeter = (r) => {
  return 2 * PI * r;
};

In index.js we can choose which named exports to import. In this case we only import getCircleArea, but we could also import getCirclePerimeter if we wanted.

index.js
import { getCircleArea } from "./circleUtils.js";

console.log(getCircleArea(2));

Default Exports

Use default exports when the module only does 1 operation, and all functions in that module exist to support that operation. In general we prefer named exports for clarity of what is exported and imported. Each module can only have 1 default export.

In the calcHandScore module, the only function that needs access externally is calcHandScore, which we export as a default export.

calcHandScore.js
const checkFullHouse = (hand) => {
  // Verify if card hand has a full house
};

const checkStraight = (hand) => {
  // Verify if card hand has a straight
};

const calcHandScore = (hand) => {
  let handScore = 0;
  if (checkFullHouse(hand)) {
    // Update handScore for full house
  } else if (checkStraight(hand)) {
    // Update hand score for straight
  }
  return handScore;
};

export default calcHandScore;

index.js imports the calcHandScore function, allowing it to calculate the score of a card hand without having to worry about the implementation details of how to calculate it.

Note we do not use curly braces {} when importing default exports.

index.js
// No curly braces around imported default export
import calcHandScore from "./calcHandScore.js";

const hand = ["A", "A", "A", "K", "K"];
const handScore = calcHandScore(hand);
console.log(handScore);

Additional Resources

Previous0.5: Node.jsNext0.5.2: NPM

🪨
Summary of Node Module usage in 100 seconds