Modules: require & exports
Split your code across files and use Node’s built-in toolkits — the module system at the heart of every Node app.
What you will learn
- Export and require your own modules
- Use built-in modules
- Understand CommonJS vs ES modules
Your own modules
As your program grows, putting everything in one file gets messy. Node lets you split code into modules — separate files that each do one job. A file decides what to share with module.exports, and another file pulls that in with require. Think of it like packing tools into a labelled box (module.exports) and then opening that box in another room (require).
First, a file that exports two helper functions so other files can use them:
// math.js
function add(a, b) { return a + b; }
function multiply(a, b) { return a * b; }
module.exports = { add, multiply };The last line is the key part: module.exports = { add, multiply } hands out an object containing both functions. Anything not on module.exports stays private to this file. Now another file can import and use them:
// app.js
const math = require("./math");
console.log(math.add(2, 3)); // 5
console.log(math.multiply(4, 5)); // 20Note: Output:
5
20
require("./math") loads the file math.js from the same folder (the ./ means "right here"; you leave off the .js). It returns whatever that file put on module.exports — the object with add and multiply — which we store in math. So math.add(2, 3) runs the add function and prints 5, and math.multiply(4, 5) prints 20.
Built-in modules
Node ships with useful modules you can require without installing anything — like fs (files), http (servers), path (file paths) and os (info about the computer). Notice these have no ./ in front: that tells Node it is a built-in module, not one of your own files.
const os = require("os");
console.log("Platform:", os.platform());
console.log("Free memory:", os.freemem());Note: Output:
Platform: darwin
Free memory: 837230592
(Your values will differ.) require("os") loads Node’s built-in os module. os.platform() reports the operating system (darwin means macOS, win32 is Windows, linux is Linux), and os.freemem() reports the free memory in bytes. You did not install anything — these tools come with Node.
Note: This require/module.exports style is called CommonJS — the classic Node system. Modern Node also supports ES modules (import/export) if you set "type": "module" in package.json. Both are common; CommonJS is shown here.
Q. How do you bring a module into a Node file (CommonJS)?
✍️ Practice
- Create a
utils.jsthat exports two functions and use them inapp.js. - Use the built-in
osmodule to print info about your computer.
🏠 Homework
- Build a
calculator.jsmodule with add, subtract, multiply, divide and use it from another file.