File Extension Conventions
You'll learn how Node.js uses file extensions (.js, .mjs, .cjs) to determine which module system to use for a file.
Why Extensions Matter
In Node.js, the file extension acts like a label on a package that tells the system what's inside. Just as you'd label a box "Fragile" or "Heavy," JavaScript files use extensions to signal their module type. Node.js reads these labels to know how to load and execute your code.
The Three Extensions
.js — The Chameleon
This is the default extension. Its behavior depends on the nearest package.json file's "type" field:
- If
"type": "module",.jsfiles use ES Modules (ESM) - If
"type": "commonjs"(or no type field),.jsfiles use CommonJS (CJS)
.mjs — Always ES Modules
The m stands for "module." Files with .mjs are always treated as ES Modules, regardless of package.json settings. Use this when you need ESM in a CommonJS project.
.cjs — Always CommonJS
The c stands for "Commonjs." Files with .cjs are always treated as CommonJS modules, regardless of package.json settings. Use this when you need CommonJS in an ES Module project.
When to Use Each
.js: Use for most files when your whole project uses one system consistently.mjs: Use when you need ESM in a CommonJS-default project, or want to be explicit.cjs: Use when you need CommonJS in an ESM-default project, or for config files that must userequire()
Key Takeaway: Node.js determines module type by file extension first (.mjs = ESM, .cjs = CommonJS), then falls back to checking package.json for .js files. Use specific extensions to override defaults when mixing module systems.