Modules (require and import)

View saved

CommonJS require

Older Node style still common in tutorials and packages.

// math.js
function add(a, b) {
  return a + b;
}
module.exports = { add };

// app.js
const { add } = require("./math");
console.log(add(2, 3));

ES modules import

Add "type": "module" to package.json, or use .mjs files.

// math.mjs
export function add(a, b) {
  return a + b;
}

// app.mjs
import { add } from "./math.mjs";
console.log(add(2, 3));

Built-in modules

Node provides modules such as fs, path, http, and url.

const path = require("path");
console.log(path.join("data", "users.json"));

Choose one style per project

Mixing is possible but confusing for beginners. Pick CommonJS or ESM and stay consistent while learning.

Comments

One comment per signed-in account. Comments are saved with this page’s URL.