Skip to content

Interview PrepProcess and packages · Basics

Modules in Node.js ​

68. What is a module in Node.js? ​

The short answer

A module is a file whose variables and functions are private to it unless it explicitly exports them, and which other files can import. That keeps code organised and avoids name clashes. Node.js has three sources of modules: built-in core modules such as node:fs, your own files imported by relative path such as ./orders.js, and packages installed in node_modules imported by name such as express. Each module is loaded once and cached, so every importer gets the same instance.

ts
// pricing.ts
const VAT = 0.2                                          // private to this file
export function withVat(pence: number) { return Math.round(pence * (1 + VAT)) }

// checkout.ts
import { withVat } from './pricing.js'                   // your own module
import { randomUUID } from 'node:crypto'                 // a core module
import express from 'express'                            // a package from node_modules

Modules are singletons. The first import runs the file and caches its exports. Later imports, from anywhere, get the same cached object. That is why a database pool created in db.ts is shared by every file that imports it.

ts
// db.ts
import pg from 'pg'
export const pool = new pg.Pool({ connectionString: config.DATABASE_URL })   // created once

How Node.js finds a package import such as 'express': it looks in node_modules in the current folder, then in each parent folder up to the root, and reads the package's package.json to find its entry file, using the exports field if present (question 73).

69. What is the difference between CommonJS and ES Modules in Node.js? ​

The short answer

CommonJS is Node.js's original system, using require and module.exports, loaded synchronously when the line runs. ES Modules are the JavaScript standard, using import and export, analysed before running, loaded asynchronously, always strict, with top-level await. Node.js decides per file: .mjs is ESM, .cjs is CommonJS, and .js follows the "type" field of the nearest package.json. ESM can import CommonJS, and modern Node.js can also require ESM that has no top-level await.

The language-level differences are explained in the JavaScript module (question 66). In Node.js specifically:

CommonJSES Modules
File is this kind when.cjs, or .js with "type": "commonjs" or no type.mjs, or .js with "type": "module"
Relative importsExtension optional: require('./db')Extension required: import './db.js'
__dirname, __filenameAvailableimport.meta.dirname, import.meta.filename
Loading JSONrequire('./data.json')import data from './data.json' with { type: 'json' }
Load the other kindrequire(esm) works if the ESM has no top-level awaitimport cjs from './x.cjs' gives module.exports as the default
Conditional loadingrequire anywhereawait import() (question 67)

The extension rule surprises people moving to ESM, especially in TypeScript: you write import { pool } from './db.js' in a .ts file, because the import must name the file as it will exist after compiling.

Publishing a library for both: the exports field in package.json can point each kind of importer to its own build:

json
{
  "name": "@shop/money",
  "type": "module",
  "exports": {
    ".": {
      "import": "./dist/index.js",
      "require": "./dist/index.cjs",
      "types": "./dist/index.d.ts"
    }
  }
}

Which to choose for new code: ES Modules. The ecosystem has moved there, and many popular packages now ship ESM only.

70. What is the difference between require() and import? ​

The short answer

require() is a function call from CommonJS: it runs when that line runs, synchronously loads and executes the module, and returns its module.exports, so it can appear inside if blocks or functions. import is ES Module syntax: static import statements must be at the top level, are found and loaded before the module runs, give live bindings to exports, and allow tree shaking. The dynamic import() expression is the ESM way to load something conditionally, and returns a promise.

ts
// CommonJS
const { withVat } = require('./pricing.cjs')            // runs now, synchronously
if (process.env.ENABLE_PDF) {
  const pdf = require('./pdf.cjs')                       // allowed anywhere
}

// ES Modules
import { withVat as vat } from './pricing.js'           // hoisted: loaded before any code runs
if (process.env.ENABLE_PDF) {
  const pdf = await import('./pdf.js')                   // dynamic, returns a promise
}
require()import statementimport() expression
KindFunction callSyntax, staticExpression, dynamic
When it loadsWhen the line runsBefore the module body runsWhen the line runs
SynchronousYesLoading is asynchronousReturns a promise
Allowed inside if or functionsYesNoYes
Tree shakingNoYesPartly

import of a CommonJS package gives you module.exports as the default export, and Node.js tries to detect named exports too, so import express from 'express' and often import { Router } from 'express' both work.

71. What is module.exports? ​

The short answer

In CommonJS, every file gets a module object, and module.exports is the value that require() returns to whoever loads that file. It starts as an empty object. You either add properties to it, to export several things, or replace it entirely with a single function, class or object. Whatever module.exports holds when the file finishes running is what importers receive.

js
// money.cjs: export several things
module.exports.formatPence = (p) => `£${(p / 100).toFixed(2)}`
module.exports.CURRENCY = 'GBP'

// mailer.cjs: export one thing, replacing the object
class Mailer { send(to, body) { /* ... */ } }
module.exports = Mailer

// app.cjs
const { formatPence } = require('./money.cjs')
const Mailer = require('./mailer.cjs')

How it works underneath. Node.js wraps every CommonJS file in a function before running it, roughly:

js
(function (exports, require, module, __filename, __dirname) {
  // your file's code
})

That wrapper is why module, exports, require and __dirname exist in every CommonJS file, and why top-level variables stay private to the file.

72. What is exports, and how does it differ from module.exports? ​

The short answer

exports is just a shortcut variable that starts out pointing to the same object as module.exports. Adding properties through it, exports.formatPence = …, works, because both names point at one object. But assigning a new value to exports itself, exports = myFunction, only changes the local variable, not module.exports, so nothing is exported. require always returns module.exports. When you want to export a single value, assign to module.exports.

js
// works: adds a property to the shared object
exports.formatPence = (p) => `£${(p / 100).toFixed(2)}`

// broken: exports now points somewhere else; module.exports is still {}
exports = function sendEmail() {}

// works: replaces what require() returns
module.exports = function sendEmail() {}
at the startexportsmodule.exports{ }after exports = fnexportsmodule.exportssendEmail{ }require() returns this one
Two names, one object, until you reassign. Both names start pointing at one empty object. Reassigning exports only moves that name; module.exports, which is what require returns, is unchanged.

A simple rule: use module.exports = … for a single export, module.exports.name = … or exports.name = … for several, and never mix reassignment of module.exports with exports.name in the same file, because the properties added through exports would be lost.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Node.js
Runtime
Memory and debugging
Data and files
Process and packages
Other topics
Nothing picked yet