Lesson 4 of 8 ~15 min
Course progress
0%

Modules and NPM

Learn about Node.js module system and package management.

Modules and NPM

Node.js uses a modular architecture that allows you to organize code into reusable pieces.

CommonJS Modules

Node.js uses the CommonJS module system by default.

Exporting Modules

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

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

module.exports = { add, subtract };

Importing Modules

// app.js
const math = require('./math');

console.log(math.add(5, 3));      // 8
console.log(math.subtract(10, 4)); // 6

ES Modules

Modern Node.js also supports ES modules:

// package.json
{
  "type": "module"
}
// math.mjs
export function add(a, b) {
  return a + b;
}

// app.mjs
import { add } from './math.mjs';
console.log(add(5, 3));

NPM (Node Package Manager)

NPM is the world’s largest software registry with over 2 million packages.

Package.json

Every Node.js project starts with a package.json:

npm init -y
{
  "name": "my-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  }
}

Installing Packages

# Install as dependency
npm install express

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

# Install globally
npm install -g typescript

Package Versions

{
  "dependencies": {
    "express": "^4.18.0",  // Compatible with 4.x.x
    "lodash": "~4.17.0",    // Compatible with 4.17.x
    "axios": "1.0.0"        // Exact version
  }
}

Core Modules

Node.js comes with built-in modules:

const fs = require('fs');
const path = require('path');
const http = require('http');
const os = require('os');

// File system operations
fs.readFile('data.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

// Path operations
const fullPath = path.join(__dirname, 'data', 'file.txt');

// System information
console.log('OS:', os.platform());
console.log('CPU:', os.cpus().length);

What is the default module system in Node.js?

CommonJS
ES Modules
AMD
UMD

Which command initializes a new Node.js project?

npm start
npm init
npm create
npm new

What does '^' mean in package version '^4.18.0'?

Exact version
Greater than or equal
Compatible with 4.x.x
Any version