Sub topic 7
Running Modules in Node.js
This chapter assumes you can run a file with node from a terminal and know what a package.json file is. It also builds on the earlier chapters about export and import syntax and about module specifiers.
Node.js supports two module systems: ES modules and the older CommonJS format, which uses require(). Before Node runs a file, it has to decide which system the file uses. That decision depends on the file extension and the nearest package.json, not only on the code inside the file.
How Node Decides a File's Module Type
| Extension | No `type` field or `"type": "commonjs"` | `"type": "module"` |
|---|---|---|
| `.mjs` | ES module | ES module |
| `.cjs` | CommonJS | CommonJS |
| `.js` | CommonJS | ES module |
Use .mjs for a single ES module file in a CommonJS project. Use the type field when the whole package uses ES modules.
Configuring a Package
This package.json makes every .js file in the package an ES module and declares the package's public entry point:
{
"name": "geometry",
"version": "1.0.0",
"type": "module",
"exports": {
".": "./src/index.js"
}
}When another project runs import { area } from 'geometry', Node resolves that import to src/index.js. The exports field also seals the package. A deep import such as geometry/src/math.js fails with ERR_PACKAGE_PATH_NOT_EXPORTED unless that path is listed in exports. This lets you control what consumers can rely on.
A Working Example
// src/math.js
export function area(radius) {
return Math.PI * radius * radius;
}// src/index.js
import { area } from './math.js';
import { readFile } from 'node:fs/promises';
console.log(area(2).toFixed(2));
const pkg = JSON.parse(await readFile('package.json', 'utf8'));
console.log(pkg.name);Run it from the package root:
node src/index.jsIt prints 12.57 and then geometry.
Common Errors
- Missing file extension. In an ES module,
import { area } from './math'fails withERR_MODULE_NOT_FOUND. Node does not guess extensions or look forindex.jsfiles for relative specifiers. Write./math.js. SyntaxError: Cannot use import statement outside a module. Node loaded the file as CommonJS. Rename it to.mjsor add"type": "module".ReferenceError: require is not defined in ES module scope. The file is an ES module, sorequire,module.exports,__dirname, and__filenamedo not exist. Later chapters cover the replacements:import.metaandcreateRequire.- Built-in modules. Prefer the
node:prefix, as innode:fs/promises. It makes clear that the import is a built-in module and not a package from npm.
Exercise
A project's package.json has no "type" field. It contains app.js, which uses import statements, and util.mjs, which uses export. Running node app.js fails with "Cannot use import statement outside a module". Give two different fixes.
Show answer
Without a "type" field, a .js file is CommonJS (older Node versions report this error instead of detecting the syntax). Fix 1: add "type": "module" to package.json so that .js files are ES modules. Fix 2: rename app.js to app.mjs and run node app.mjs. util.mjs already works either way because the .mjs extension always means ES module. Also check that the import specifier includes the extension, for example './util.mjs'.
Exercise
Your package's exports field lists only ".": "./src/index.js". A user writes import { area } from 'geometry/src/math.js'. What happens, and how could you allow it?
Show answer
Node throws ERRPACKAGEPATHNOTEXPORTED because that subpath is not listed in exports. To allow it, add an entry such as "./math": "./src/math.js" and have users import 'geometry/math'. The other option is to re-export area from index.js.