Modules: Import and Export — Node.js

Every file is a module with its own space, and only what is exported can be used by other files. Node has two ways to write modules. CommonJS, Node's original…

In a restaurant kitchen, the cook has plenty of ingredients and tools. Only the plates set on the pass (the counter where finished plates wait) reach the guests' tables. The rest stays in the kitchen.

JavaScript files in Node work the same way. Every file is a module that keeps its contents to itself, like that kitchen. Other files can use only what the file puts on the "pass". In code, putting something on the pass is called export, and other files take it with import.

One file, one module

The notes-api project is growing. We move the notes data and the functions that fetch it into their own file, notes.js, so app.js stays short. Every file in Node has its own space: variables in notes.js can't be seen from app.js, unless they are exported.

Node has two ways to write modules:

CommonJS: module.exports and require

Here is notes.js, the file that shares two functions, then app.js, the file that uses them:

// notes.js
const notes = [
  { id: 1, title: "Groceries", content: "buy 5 kg of rice" },
  { id: 2, title: "Study", content: "Node.js chapter" },
];

function getAll() {
  return notes;
}

function getById(id) {
  return notes.find((n) => n.id === id);
}

module.exports = { getAll, getById };
// app.js
const { getAll, getById } = require("./notes");

console.log(getAll().length + " notes");
console.log(getById(2).title);

Run app.js in the terminal:

$ node app.js
2 notes
Study

There is also the exports shortcut. This variable points to the same object as module.exports. So if math.js holds exports.add = (a, b) => a + b;, the function add goes into that object too. Another file can write const math = require("./math"), then call math.add(2, 3) and get 5.

You take Node's built-in modules by name alone, with no ./: require("fs"). You can also write require("node:fs"), to make clear that fs is built into Node.

What isn't exported stays in the file

Change the last line of notes.js to module.exports = { getAll };. app.js doesn't change, so it still calls getById(2). First guess what happens, then run it again:

2 notes
/home/budi/notes-api/app.js:4
console.log(getById(2).title);
            ^

TypeError: getById is not a function

require returns only { getAll }. So getById in app.js holds undefined, and undefined can't be called like a function. Line 3 ran and printed 2 notes. The program stopped at line 4, the getById(2) line (the line numbers don't count the // app.js label).

ES Modules: export and import

Here are the same two files, written the ES Modules way. export goes in front of each function, in place of module.exports:

// notes.js
export function getAll() { return notes; }
export function getById(id) { return notes.find((n) => n.id === id); }

// app.js
import { getAll, getById } from "./notes.js";

Two rules that differ from CommonJS:

A file can also have one default export. For example, export default function greet() {...} is taken with import greet from "./greet.js";, without curly braces.

package.json picks the kind

Node reads a .js file as CommonJS or ES Modules according to the "type" field in package.json:

"type" .js is read as If you write the other kind
"commonjs" CommonJS import fails: SyntaxError: Cannot use import statement outside a module
"module" ES Modules require fails: ReferenceError: require is not defined in ES module scope, you can use import instead
missing CommonJS, but when Node finds import/export, the file is read again as ES Modules it runs, with a MODULE_TYPELESS_PACKAGE_JSON warning

npm init -y on Node 24 writes "type": "commonjs". For a new project that uses import, change it to "module". A single file can also choose for itself through its extension: .cjs is always CommonJS, .mjs is always ES Modules.

Which one to pick:

Kind When to pick it
ES Modules ("type": "module") A new project. It is the JavaScript standard, and some npm packages are now available only as ES Modules.
CommonJS Older code and many Express tutorials (Express is a framework for building servers, used later in this track). This track uses CommonJS because npm init -y writes "type": "commonjs", and most Express examples you will meet are still written with CommonJS.

The two kinds of file can use each other. An ES Modules file can import a CommonJS file. The safest way is the default import (no curly braces): import notes from "./notes.cjs". Since Node 22.12, a CommonJS file can also require("./greet.mjs"), as long as greet.mjs does not use await outside a function. If it does, Node refuses with ERR_REQUIRE_ASYNC_MODULE.

In the exercise: two files in one editor

The exercise has only one editor, so the "two files" are written in one place. It holds the functions add(a, b) and subtract(a, b), the line module.exports = { add, subtract };, then require('./module'). In the exercise's simulator (a program that imitates Node), require with a relative path (an address that starts with ./) returns that same file's module.exports. On your laptop, split it into math.js and app.js. add(10, 3) gives 13, and subtract(10, 3) gives 7.

⚠️ Slips that make export and import miss

TL;DR: Every file is a module with its own space, and only what is exported can be used by other files. Node has two ways to write modules. CommonJS, Node's original way: module.exports = { getAll, getById } (or exports.name = ...), then const { getAll } = require("./notes"). The .js extension may be left out, and built-in modules are taken by name, require("fs"). ES Modules, the JavaScript standard that browsers use too: export, then import { getAll } from "./notes.js", and the extension is required. "type" in package.json picks the kind: "commonjs" or "module". Using a name that isn't exported gives TypeError: ... is not a function in CommonJS. In ES Modules it gives a SyntaxError before any line runs.

⚡ Put it on the pass with module.exports

Write:

// notes.js
function getAll() {
  return notes;
}

function getById(id) {
  return notes.find((n) => n.id === id);
}

module.exports = { getAll, getById };

Meaning: In Node, every file is a module with its own space. module.exports is like the pass in a restaurant kitchen (the counter where finished plates wait): only what goes there can be used by other files. This way is called CommonJS, Node's original way. The notes array, the data that getAll and getById use, isn't put there, so it stays private: only the code in notes.js can use it.

⚡ Take it with require

Write:

// app.js
const { getAll, getById } = require("./notes");

console.log(getAll().length + " notes");
console.log(getById(2).title);
Guess first: module.exports becomes just { getAll }. What happens on the getById(2) line?

TypeError: getById is not a function. require returns only { getAll }, so getById holds undefined.

Meaning: require("./notes") runs notes.js, then returns its module.exports. ./ means in the same folder, and .js may be left out.

⚡ ES Modules: import, the extension is required

Write:

import { getAll, getById } from "./notes.js";

Meaning: ES Modules are the JavaScript standard way, the same as in the browser: export shares, import takes. Here the .js extension must be written. The "type" field in package.json picks the way: "commonjs" for require, "module" for import.

What you will learn