TExcelTAD
Home › Node.js › Node.js Modules

Node.js Modules

A module is a JavaScript file whose variables stay private unless you explicitly export them. Splitting a program into modules keeps each file small and lets you reuse code. Node supports two module systems:

CommonJS (CJS) ES modules (ESM)
Import const x = require("./x") import x from "./x.js"
Export module.exports = ... / exports.name = ... export / export default
Loading synchronous, at the line where require runs resolved before the code runs
File extension .cjs, or .js by default .mjs, or .js with "type": "module"
Top-level await no yes
__dirname yes use import.meta.dirname

ES modules are the JavaScript standard and the recommended choice for new code. CommonJS is still everywhere in existing packages, so you need to read both.

CommonJS: require and module.exports

Imagine two files:

js
// math.cjs
function add(a, b) { return a + b; }
const PI = 3.14159;
module.exports = { add, PI };
js
// app.cjs
const { add, PI } = require("./math.cjs");
console.log(add(2, 3), PI);

This playground creates math.cjs on disk and then requires it, so you can see the whole flow in one run:

node · try it yourself
const fs = require("node:fs");

fs.writeFileSync("math.cjs", `
function add(a, b) { return a + b; }
const PI = 3.14159;
let calls = 0;
function counted() { return ++calls; }
module.exports = { add, PI, counted };
`);

const { add, PI, counted } = require("./math.cjs");
console.log(add(2, 3), PI);

// Modules are cached: requiring again returns the same object.
const again = require("./math.cjs");
counted();
console.log("calls after two counted():", again.counted());
console.log("same object:", again === require("./math.cjs"));

fs.unlinkSync("math.cjs");
5 3.14159
calls after two counted(): 2
same object: true

A module's code runs only once, the first time it is required. Later require calls return the cached module.exports object.

ES modules: import and export

js
// shapes.mjs
export const unit = "cm";
export function area(w, h) { return w * h; }
export default function describe(w, h) {
  return `${w}x${h} ${unit}`;
}
js
// app.mjs
import describe, { area, unit } from "./shapes.mjs";

ESM needs the full file name including the extension in relative imports. Here is a runnable version that writes the module first and loads it with a dynamic import():

node · try it yourself
import { writeFile, rm } from "node:fs/promises";

await writeFile("shapes.mjs", `
export const unit = "cm";
export function area(w, h) { return w * h; }
export default function describe(w, h) { return w + "x" + h + " " + unit; }
`);

const shapes = await import("./shapes.mjs");
console.log(shapes.default(3, 4));
console.log("area:", shapes.area(3, 4), shapes.unit);
console.log("export names:", Object.keys(shapes));

await rm("shapes.mjs");
3x4 cm
area: 12 cm
export names: [ 'area', 'default', 'unit' ]

import() returns a promise for the module namespace object; the default export appears under the key default. Static import statements at the top of a file are more common — dynamic import() is for loading modules conditionally or on demand.

Choosing the module system for .js files

Node decides how to treat a .js file from the nearest package.json:

json
{
  "name": "my-app",
  "type": "module"
}
"type" field .js means Force the other with
missing or "commonjs" CommonJS .mjs
"module" ES module .cjs

Tip: Since Node 22.12, CommonJS code can require() a synchronous ES module, and ES modules can always import a CommonJS module. Mixing is much less painful than it used to be.

File paths inside a module

Both systems can tell you where the current file lives — handy for reading files next to your code:

node · try it yourself
import path from "node:path";

console.log(typeof import.meta.dirname);
console.log(path.basename(import.meta.filename));
console.log(import.meta.url.startsWith("file://"));
string
main.mjs
true

In CommonJS the equivalents are the variables __dirname and __filename.

Test yourself

In CommonJS, how do you make a function greet available to other files?

  1. export greet
  2. module.exports = { greet }
  3. public greet
  4. require.export(greet)

With "type": "module" in package.json, how is a .cjs file treated?

  1. As an ES module
  2. As CommonJS
  3. As JSON
  4. It is an error

What happens when you require the same module twice?

  1. Its code runs twice
  2. The cached exports object is returned
  3. Node throws an error
  4. A copy of the exports is made