Modules: import, export and Built-ins
Split your code into files called modules. Node supports two systems:
Splitting code into modules keeps each file focused on one job and makes code reusable. Node supports two module systems; new projects should use ES modules (import/export), but you'll still see require() in older code and tutorials.
- ES modules (modern, same as the browser):
import/export. Use.mjsfiles, or add"type": "module"to package.json. - CommonJS (older, still common):
require()/module.exports, in.jsor.cjsfiles.
Example
Example
// tax.mjs
export const GST_RATE = 18;
export function addGst(price) { return Math.round(price * (1 + GST_RATE / 100)); }
export default function formatINR(n) { return "Rs " + n.toLocaleString("en-IN"); }The same in CommonJS
Example
// tax.cjs
function addGst(price) { return Math.round(price * 1.18); }
module.exports = { addGst };
// main.cjs
const { addGst } = require("./tax.cjs");
console.log(addGst(2500));Built-in modules
Node comes with useful modules. Import them with the node: prefix:
Example
Use
path.join instead of gluing folder names with "/" - it uses the right separator for each system. (On Windows the first line prints uploads\invoices\INV-1042.pdf.)Key points
- export shares code; import uses it.
- CommonJS uses require and module.exports.
- Built-in modules use the node: prefix.
📝 Test yourself
1. Which keyword shares a function from an ES module?
2. What does the node: prefix mean?
3. Fill in the CommonJS way to load a module:
const { addGst } = ("./tax.cjs");
