🏠 Home / Hub

🟢 Node.js Lesson 02 — Modules & NPM

← Back to Node.js Menu  |  🏠 Hub

1. CommonJS Modules (require / module.exports)

// math.js — create a module
function add(a, b) { return a + b; }
function subtract(a, b) { return a - b; }

module.exports = { add, subtract };
// OR export single:
// module.exports = add;

// app.js — use the module
const math = require('./math');   // ./ = same folder
console.log(math.add(5, 3));      // 8
console.log(math.subtract(5, 3)); // 2

// Destructure import
const { add, subtract } = require('./math');

// Built-in modules (no install needed)
const fs   = require('fs');       // File System
const path = require('path');     // Path utilities
const http = require('http');     // HTTP server
const os   = require('os');       // OS info
const crypto = require('crypto'); // Encryption

2. ES Modules (import / export) — Modern

// package.json မှာ "type": "module" ထည့်ရ OR .mjs extension သုံး

// math.mjs
export function add(a, b) { return a + b; }
export const PI = 3.14159;
export default class Calculator { }

// app.mjs
import { add, PI } from './math.mjs';
import Calculator from './math.mjs';  // default import
import * as math from './math.mjs';    // all exports

// Dynamic import (lazy load)
const { add } = await import('./math.mjs');

// CommonJS vs ESM
// CommonJS: synchronous, older, .js default
// ESM:      async, modern, tree-shakable, browser compatible
Node 18+ မှာ ES Modules ကို default support ရပြီ — new projects မှာ ESM prefer

3. Built-in Modules Quick Reference

const path = require('path');
path.join('/home', 'user', 'file.txt');  // /home/user/file.txt
path.basename('/home/user/file.txt');    // file.txt
path.dirname('/home/user/file.txt');     // /home/user
path.extname('file.txt');                // .txt
path.resolve('src', 'app.js');          // absolute path

const os = require('os');
os.platform();    // 'win32' | 'linux' | 'darwin'
os.cpus().length; // CPU cores count
os.totalmem();    // total memory in bytes
os.homedir();     // C:\Users\Ko

const crypto = require('crypto');
crypto.randomUUID();                // UUID v4
crypto.createHash('sha256').update('hello').digest('hex');

4. NPM — Node Package Manager

# Initialize project
npm init          # interactive setup
npm init -y       # skip questions (default values)
# → creates package.json

# Install packages
npm install express         # production dependency
npm install -D nodemon      # dev dependency only
npm install -g @quasar/cli  # global install

# Uninstall
npm uninstall express

# List installed packages
npm list --depth=0

# Outdated packages
npm outdated

# Update packages
npm update

# Run scripts (from package.json scripts section)
npm run dev
npm run build
npm start         # shortcut for npm run start
// package.json
{
  "name": "my-app",
  "version": "1.0.0",
  "type": "module",       // ESM enable
  "scripts": {
    "start":  "node server.js",
    "dev":    "nodemon server.js",    // auto-restart on save
    "build":  "...",
    "test":   "jest"
  },
  "dependencies": {
    "express": "^4.18.2",
    "mysql2":  "^3.6.0"
  },
  "devDependencies": {
    "nodemon": "^3.0.1"   // only for development
  }
}
💡 node_modules folder = .gitignore ထဲ ထည့် — git ထဲ မ push နဲ့ | npm install ကနေ restore ဖြစ်

5. nodemon — Auto Restart

# Install
npm install -D nodemon

# Run with nodemon
npx nodemon server.js

# package.json script
{
  "scripts": {
    "dev": "nodemon server.js"
  }
}
npm run dev

# nodemon.json — config file (optional)
{
  "watch": ["src"],
  "ext": "js,json",
  "ignore": ["node_modules"],
  "delay": 1000
}

← Node.js 01  |  Next: Node.js 03 → File System →

📌 Study Checklist