Skip to main content

NPM and Modules

Node.js programs are rarely contained within a single file. Large applications require you to split logic into modules and import third-party libraries.

1. Node Package Manager (NPM)​

NPM is the default package manager for Node.js. It connects developers to an enormous online registry of open-source libraries.

When you initialize a project using npm init, it generates a package.json file. This file acts as the central blueprint for your project, recording exactly which packages are installed and what versions they are locked to.

# Initialize a new project
npm init -y

# Install an external package (e.g., express)
npm install express

Packages are downloaded into the node_modules folder, which should ideally be ignored by Git.

2. Module Formats​

Node.js supports two distinct module formats for importing and exporting files.

CommonJS (CJS)​

The legacy system original to Node.js. It relies on the require() function to pull variables and functions synchronously.

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

// app.js
const add = require('./math');
console.log(add(5, 5));

ES Modules (ESM)​

The modern, standardized syntax used in modern frontend frameworks (React, Angular). To use ES Modules in Node, you must add "type": "module" to your package.json file.

// package.json
{
"name": "my-app",
"type": "module"
}
// math.js
export function add(a, b) { return a + b; }

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