Node.js Beginner

Node.js Modules and NPM: Organizing and Managing Code

CodingerWeb
CodingerWeb
19 views 45 min read

Understanding Node.js Modules

Modules are the building blocks of Node.js applications. They allow you to organize code into reusable components and manage dependencies effectively.

Types of Modules

  • Core Modules: Built-in modules like fs, http, path
  • Local Modules: Custom modules you create
  • Third-party Modules: Modules from npm registry

Creating Your First Module

Create math.js:

// math.js
function add(a, b) {
    return a + b;
}

function subtract(a, b) {
    return a - b;
}

function multiply(a, b) {
    return a * b;
}

function divide(a, b) {
    if (b === 0) {
        throw new Error("Division by zero is not allowed");
    }
    return a / b;
}

// Export functions
module.exports = {
    add,
    subtract,
    multiply,
    divide
};

Using Your Module

Create calculator.js:

// calculator.js
const math = require("./math");

console.log("Addition: 5 + 3 =", math.add(5, 3));
console.log("Subtraction: 10 - 4 =", math.subtract(10, 4));
console.log("Multiplication: 6 * 7 =", math.multiply(6, 7));
console.log("Division: 15 / 3 =", math.divide(15, 3));

Core Modules Example

// Using built-in modules
const fs = require("fs");
const path = require("path");
const os = require("os");

// File system operations
console.log("Current directory:", process.cwd());

// Operating system info
console.log("Platform:", os.platform());
console.log("CPU architecture:", os.arch());
console.log("Free memory:", os.freemem());

// Path operations
const filePath = path.join(__dirname, "data", "users.txt");
console.log("File path:", filePath);

Introduction to NPM

NPM (Node Package Manager) is the default package manager for Node.js:

# Initialize a new project
npm init

# Install a package
npm install lodash

# Install as development dependency
npm install --save-dev nodemon

# Install globally
npm install -g nodemon

Package.json File

{
  "name": "my-node-app",
  "version": "1.0.0",
  "description": "My first Node.js application",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js"
  },
  "dependencies": {
    "lodash": "^4.17.21"
  },
  "devDependencies": {
    "nodemon": "^2.0.15"
  }
}

Exercise

Create a utility module with functions for:

  1. Converting temperature (Celsius to Fahrenheit and vice versa)
  2. Generating random numbers within a range
  3. Formatting dates

What's Next?

In the next lesson, we'll explore the Node.js event loop and asynchronous programming concepts.