Getting Started

Modules and npm

Understand CommonJS and ES modules, and how to manage packages with npm.

Node.js Modules

Node.js organizes code into modules. Each file is a module. You can export values and import them in other files.

CommonJS (require/module.exports)

The traditional Node.js module system. Still widely used.

ES Modules (import/export)

The modern JavaScript module system. Supported in Node.js 12+ with .mjs extension or "type": "module" in package.json.

npm (Node Package Manager)

npm is the world's largest software registry. Use it to install, share, and manage packages.

Key npm commands:

  • npm init — create a new project
  • npm install package — install a package
  • npm install -D package — install as dev dependency
  • npm run script — run a script from package.json

Example

nodejs
// math.js - CommonJS export
function add(a, b) { return a + b; }
function subtract(a, b) { return a - b; }

module.exports = { add, subtract };

// main.js - CommonJS import
const { add, subtract } = require('./math');
console.log(add(5, 3));      // 8
console.log(subtract(5, 3)); // 2

// ES Modules (math.mjs)
export function multiply(a, b) { return a * b; }
export default function divide(a, b) { return a / b; }

// ES Modules import
import divide, { multiply } from './math.mjs';

// Built-in modules (no install needed)
const path = require('path');
const fs = require('fs');
const os = require('os');

console.log(path.join(__dirname, 'data', 'file.txt'));
console.log(os.cpus().length);

// package.json scripts
// {
//   "scripts": {
//     "start": "node index.js",
//     "dev": "nodemon index.js",
//     "test": "jest"
//   }
// }
Try it yourself — NODEJS