What you'll learn
How to share code between files with modules, and how to import Node's built-in modules.
Why it matters
Real programs are many files. Modules keep each file small and focused, and let you reuse code instead of copying it.
Explanation
A module is just a file. It chooses what to share with export, and other files bring it in with import.
// math.js
export function add(a, b) {
return a + b;
}// main.js
import { add } from "./math.js";
console.log(add(2, 3));For Node to treat your files as modern ES modules, either name them .mjs or put "type": "module" in package.json.
Node also ships built-in modules that you import with the node: prefix: node:fs (files), node:path (file paths), node:os (system info).
Example
Two files, math.mjs and main.mjs:
// math.mjs
export function add(a, b) {
return a + b;
}
export const PI = 3.14159;// main.mjs
import { add, PI } from "./math.mjs";
import path from "node:path";
console.log(add(2, 3));
console.log(PI);
console.log(path.basename("/home/asha/notes.txt"));Run with node main.mjs.
Step-by-step walkthrough
math.mjsexports a function and a constant. Nothing else in the file is visible outside.main.mjsimports exactly those two names with curly braces.- The path to your own file starts with
./. Built-ins use thenode:prefix. path.basenamereturns the last part of a path:notes.txt.
Try it yourself
Add a multiply export to math.mjs and print multiply(4, 5). Press the button to see the output of the original main.mjs.
Common mistakes
- Forgetting
./on your own files:import "math.mjs"looks for a package. - Missing the file extension in ES module imports.
- Mixing
requireandimportin the same file. - Not enabling ES modules with
.mjsor"type": "module".
Quick quiz
Summary
- A module is a file;
exportshares,importuses. - Built-in modules are imported with the
node:prefix. - Use
.mjsor"type": "module"for ES modules.
Next: npm and installing packages.