beginner 16 min read

Modules & NPM

Understanding the module system, creating and requiring modules, and managing packages with npm.

CommonJS Modules

Node.js uses the CommonJS module system by default. Each file is treated as a separate module.

// math.js\nconst add = (a, b) => a + b;\nconst subtract = (a, b) => a - b;\n\nmodule.exports = { add, subtract };\n\n// app.js\nconst math = require('./math');\nconsole.log(math.add(5, 3)); // 8

ES Modules (ESM)

Node.js also supports ES modules. Use .mjs extension or set "type": "module" in package.json.

// utils.mjs\nexport const greet = (name) => `Hello, ${name}!`;\n\n// main.mjs\nimport { greet } from './utils.mjs';\nconsole.log(greet('Node'));

NPM Basics

npm init -y          # Initialize a project\nnpm install express  # Install a package\nnpm install -g nodemon # Install globally\nnpm update           # Update all packages\nnpm uninstall axios  # Remove a package

Examples

// File: logger.js
const chalk = (str) => `\x1b[36m${str}\x1b[0m`;

const info = (msg) => console.log(`[INFO] ${msg}`);
const error = (msg) => console.log(`[ERROR] ${msg}`);

module.exports = { info, error, chalk };

// File: app.js
const logger = require('./logger');
logger.info('Application started');
logger.error('Something went wrong');

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.