WeCodeAcademy

Node.js Modules

Code is split into modules. Each file is a module. module.exports shares things and require loads them. Node also has built-in modules such as path and os, and modern code can use import (ES modules).

ExampleNode.js
// Normally math.js is a separate file; here we simulate one with a function.
const math = { add: (a, b) => a + b, PI: 3.14159 };

const path = require("path");
console.log(math.add(2, 3), math.PI);
console.log(path.basename("/home/user/app.js"));
console.log(path.extname("notes.txt"));
console.log(path.join("a", "b", "..", "c", "file.txt"));
console.log(typeof module.exports, typeof require);
Output
5 3.14159
app.js
.txt
a/c/file.txt
object function

In a real project you would write module.exports = { add } in math.js and const { add } = require('./math') in another file.

Quick check

Which function loads a module in CommonJS?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.