Node.js BasicsBeginner8 min02 / 8

Modules & npm

Learn how to split your Node.js code into reusable modules and pull in thousands of open-source packages with npm.

Imagine trying to cook every meal in a kitchen the size of a closet, with all your ingredients, pots, and recipe books crammed into one drawer. Real kitchens have separate shelves and pantries — each item in the right place so you can find it instantly. Modules do the same thing for your JavaScript code. Instead of piling everything into one enormous file, you split code into focused files and connect them wherever needed. And npm (the Node Package Manager) is the giant supermarket where other developers have placed over two million ready-to-use packages on the shelf, free for you to grab.

#CommonJS — The Original Node.js Way

Think of it like

module.exports is a gift box

Think of every .js file as a gift box. module.exports is what you put inside the box before handing it over. When another file calls require('./yourFile'), it opens the box and gets exactly what you packed. Anything you do NOT put in the box stays private to that file — hidden from the rest of the app.

Export an object containing every function you want to share with other files.
// greet.js — pack the box
function greet(name) {
  return `Hello, ${name}!`;
}
function farewell(name) {
  return `Goodbye, ${name}!`;
}
module.exports = { greet, farewell };
require() returns whatever module.exports held. The './' prefix means "look in the current folder".
// app.js — open the box
const { greet, farewell } = require('./greet');

console.log(greet('Alice'));
console.log(farewell('Alice'));

#ES Modules — The Modern Standard

Named exports use the 'export' keyword. A default export is the "main thing" the file provides — one per file. ESM works in browsers too, unlike CommonJS.
// mathUtils.mjs — named and default exports
// ESM uses import/export keywords from the JS spec itself.
// Enable it by naming the file .mjs, or add "type":"module" in package.json.
export function add(a, b) { return a + b; }
export function multiply(a, b) { return a * b; }
export default function square(n) { return n * n; }
The default import can have any name you choose. Named imports must match the exported name exactly.
// main.mjs
import square, { add, multiply } from './mathUtils.mjs';

console.log(add(3, 4));      // named import
console.log(multiply(3, 4)); // named import
console.log(square(5));      // default import
Common mistake

You cannot mix require and import in the same file

CommonJS (require) and ESM (import) are two separate systems. A .js file using require() cannot also use import at the top level, and vice versa. Pick one style per project. For new projects, ESM is the recommended choice — it is the future of JavaScript modules.

#npm, package.json, and Installing Packages

Every Node.js project starts with a package.json — a structured recipe card that records the project's name, version, and all the packages it depends on. Create one by running npm init -y in your project folder. Then install any package with npm install <name>.

After installing, Node creates a node_modules/ folder (never edit by hand) and a package-lock.json (exact version snapshot for teammates). Add node_modules/ to your .gitignore — teammates restore it with npm install.

npm init -y generates package.json instantly. npm install adds chalk to node_modules/ and records it in package.json.
# Set up a new project
mkdir my-app && cd my-app
npm init -y

# Install a package (adds terminal colour)
npm install chalk
No file path needed — just the package name. Node finds it in node_modules/ automatically.
// index.js — use the installed package
const chalk = require('chalk');

console.log(chalk.green('Success!'));
console.log(chalk.red.bold('Error!'));
console.log(chalk.blue('Info:'), 'server is running');
Quick check

You write `module.exports = { greet };` in greet.js. In another file you call `const result = require('./greet');`. What does `result` hold?

Key takeaways

  • Modules let you split code into focused files and share only what you explicitly export — keeping the rest private.
  • CommonJS uses require() and module.exports; ES Modules use import and export. Do not mix them in the same file.
  • npm is both a CLI tool and a huge registry. package.json records dependencies; node_modules/ stores them locally.
  • Run npm install <package-name> to add a library. Teammates restore everything with a plain npm install.
  • Semantic versioning (MAJOR.MINOR.PATCH) and the ^ prefix in package.json keep you on safe, compatible updates automatically.
Practice challenges
Test yourself · earn XP
0/4
Predict the output#1

greet.js exports an object. What does this program print?

predict-output
// greet.js
function greet(name) {
  return `Hello, ${name}!`;
}
module.exports = { greet };

// app.js
const { greet } = require('./greet');
console.log(greet('Alice'));
Fix the bug#2

This CommonJS import doesn't find the local file — what's wrong?

fix-bug
// app.js — greet.js sits in the same folder
const { greet } = require('greet');

console.log(greet('Bob'));
Fill in the blank#3

Complete this ES Module so main.mjs can import add as a named import and square as the default import.

// mathUtils.mjs
export function add(a, b) { return a + b; }
export  function square(n) { return n * n; }
Reorder the lines#4

Order these terminal commands to create a new project and install the chalk package.

1
npm init -y
2
npm install chalk
3
mkdir my-app && cd my-app
Your turn
Practice exercise

Create a small Node.js project using CommonJS modules.

  1. In mathUtils.js, export two functions: double(n) which returns n * 2, and isEven(n) which returns true when n is even.
  2. In index.js, require those functions and log the results of calling double(7) and isEven(4).

Bonus: run npm install chalk and colour the output — green for even results, red for odd.

Try it yourself — a starting point to build on:

starter.js
// mathUtils.js
// TODO: write and export double(n) and isEven(n)


// index.js
const { double, isEven } = require('./mathUtils');

// TODO: log double(7) and isEven(4)