Node.js Modules

A module is a file that exports values (functions, objects, classes, or constants) that other files can import. Modules let you split your code into small, focused files instead of one large file.

Two module systems

Node.js supports two module systems. Knowing the difference matters because the syntax is different and you will encounter both.

FeatureCommonJS (CJS)ES Modules (ESM)
Importrequire()import
Exportmodule.exports / exportsexport / export default
File extension.js (default).mjs or .js with "type": "module"
When it loadsAt runtime (synchronous)At parse time (static)
Used inMost existing Node codeModern Node.js, browsers

CommonJS (require and module.exports)

CommonJS is the original Node module system. Most npm packages, tutorials, and Node code you encounter today still use it.

Export from a file:

// math.js
const add = (a, b) => a + b;
const multiply = (a, b) => a * b;

module.exports = { add, multiply };

Import in another file:

// app.js
const { add, multiply } = require('./math');

console.log(add(2, 3));      // 5
console.log(multiply(4, 5)); // 20

Importing core modules and npm packages works the same way:

const fs = require('fs');           // core module
const express = require('express'); // npm package
const config = require('./config'); // local file

ES Modules (import and export)

ES modules use the import and export keywords from modern JavaScript. This is the same module system used in the browser. New projects increasingly prefer this.

To use ES modules in Node.js, do one of these:

  • Add "type": "module" to your package.json, or
  • Use the .mjs file extension
{
  "name": "my-app",
  "type": "module"
}

Named exports:

// math.js
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;

Default export:

// logger.js
export default function log(message) {
  console.log(`[LOG] ${message}`);
}

Importing:

// app.js
import { add, multiply } from './math.js'; // named imports (must include .js extension)
import log from './logger.js';             // default import

import fs from 'fs';                       // core module
import express from 'express';             // npm package

ES modules require the .js extension in relative import paths. CommonJS does not.

Which should you use?

  • If you are working on an existing project that uses require(), stick with CommonJS.
  • If you are starting a new project, ES modules are the modern choice. Add "type": "module" to package.json.
  • If you are writing a package to publish on npm, be aware that supporting both systems requires extra setup.