Split your code across files. Learn CommonJS (require/module.exports) and modern ES Modules (import/export), how to pick one, and the global objects available everywhere.
Why: a module is just a file. Splitting code into files keeps each one small and focused. Each file decides what to share (export) with other files, and other files pick what they want (import). Node has two systems for this: the older CommonJS and the modern ES Modules.
Why: CommonJS is the original Node.js module system. You share things by assigning to module.exports, and load them with the require() function. It is still everywhere in existing projects.
// math.js
function add(a, b) {
return a + b
}
function subtract(a, b) {
return a - b
}
// share these two functions
module.exports = { add, subtract }// app.js
const { add, subtract } = require('./math')
console.log(add(2, 3)) // 5
console.log(subtract(5, 1)) // 4Why: ES Modules (ESM) are the official, modern JavaScript standard — the same import/export syntax used in browsers. To use it in Node, add "type": "module" to your package.json (or name files .mjs). Prefer this for new projects.
// package.json — opt in to ES Modules
{
"type": "module"
}// math.js
export function add(a, b) {
return a + b
}
// a "default" export — the file's main thing
export default function greet(name) {
return 'Hello, ' + name
}// app.js
import greet, { add } from './math.js'
console.log(add(2, 3)) // 5
console.log(greet('Ada')) // Hello, AdaWhy: Node ships with built-in modules (like the file system or path tools). Use the "node:" prefix to make it clear they are built in.
// app.js
// built-in module (note the node: prefix)
import path from 'node:path'
// your own file (starts with ./ or ../)
import { add } from './math.js'Why: a few things are always available without importing. process holds info about the running program, console prints output, and global. This is the global namespace.
// app.js
console.log(process.version) // Node version, e.g. v22.0.0
console.log(process.platform) // 'win32', 'darwin', or 'linux'