← Back to Examples
npm & Modules
1. npm Project Setup
$ mkdir my-project
$ cd my-project
$ npm init -y
package.json
{
"name": "my-project",
"version": "1.0.0",
"description": "A sample Node.js project",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": ["nodejs", "learning"],
"author": "Your Name",
"license": "MIT",
"dependencies": {
"express": "^4.18.2"
},
"devDependencies": {
"nodemon": "^3.0.1"
}
}
2. Installing Packages
$ npm install express
$ npm i express
$ npm install --save-dev nodemon
$ npm i -D nodemon
$ npm install -g nodemon
$ npm install express@4.18.2
$ npm install
$ npm uninstall express
$ npm list
$ npm list --depth=0
$ npm outdated
3. Project Structure
my-project/
node_modules/
package.json
package-lock.json
.gitignore
index.js
src/
routes/
users.js
middleware/
auth.js
utils/
helpers.js
.gitignore - Always add this:
node_modules/
.env
.DS_Store
*.log
4. CommonJS Modules
CommonJS is the original Node.js module system. Uses require() and module.exports.
math.js (export)
// Export multiple items
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
const PI = 3.14159;
module.exports = {
add,
subtract,
multiply,
PI
};
app.js (import)
// Import all exports
const math = require('./math');
console.log(math.add(2, 3)); // 5
console.log(math.PI); // 3.14159
// Destructured import
const { add, subtract } = require('./math');
console.log(add(10, 5)); // 15
console.log(subtract(10, 5)); // 5
// Built-in modules
const fs = require('fs');
const path = require('path');
const os = require('os');
// npm packages
const express = require('express');
5. ES Modules
ES Modules is the modern standard. Enable by adding "type": "module" to package.json or using .mjs extension.
utils.js (export)
// Named exports
export function formatDate(date) {
return date.toLocaleDateString();
}
export function capitalize(str) {
return str[0].toUpperCase()
+ str.slice(1);
}
// Default export
export default class Logger {
log(message) {
console.log(
`[${new Date().toISOString()}] ${message}`
);
}
}
app.js (import)
// Named imports
import { formatDate, capitalize }
from './utils.js';
console.log(capitalize('hello'));
// 'Hello'
// Default import
import Logger from './utils.js';
const logger = new Logger();
logger.log('App started');
// Import all
import * as utils from './utils.js';
utils.capitalize('test');
// Dynamic import (lazy loading)
async function loadModule() {
const mod = await import('./utils.js');
mod.capitalize('lazy');
}
6. CommonJS vs ES Modules
// CommonJS (CJS)
// - require() is synchronous
// - module.exports / exports
// - Default in Node.js
// - .js or .cjs extension
// - __dirname and __filename available
// ES Modules (ESM)
// - import is async (can be statically analyzed)
// - export / export default
// - Requires "type": "module" in package.json
// - .js or .mjs extension
// - Must include file extensions in imports
// - No __dirname/__filename (use import.meta.url)
// Converting __dirname in ES Modules:
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
7. Popular npm Packages
// Web Framework
// express - Fast, minimalist web framework
// Utility
// lodash - Utility functions
// dayjs - Date manipulation
// uuid - Generate unique IDs
// Database
// mongoose - MongoDB ODM
// pg - PostgreSQL client
// mysql2 - MySQL client
// Authentication
// jsonwebtoken - JWT tokens
// bcrypt - Password hashing
// Development
// nodemon - Auto-restart on changes
// dotenv - Environment variables
// eslint - Code linting
// jest - Testing framework
// API
// cors - Cross-Origin Resource Sharing
// helmet - Security headers
// morgan - HTTP request logger
← Back to Examples