Modules and NPM

Large Node.js apps are split into modules.

A module is a file or package that exposes some functionality and imports functionality from somewhere else.

Why modules exist

Without modules, all backend code would sit in one huge file.

Modules let you separate:

CommonJS

Older Node.js projects often use CommonJS.

Export:

function add(a, b) {
  return a + b
}

module.exports = { add }

Import:

const { add } = require('./math')

ES Modules

Modern JavaScript uses ES Modules.

Export:

export function add(a, b) {
  return a + b
}

Import:

import { add } from './math.js'

In Node.js, ES Modules usually need "type": "module" in package.json or .mjs files.

What is npm?

npm is the package manager commonly used with Node.js.

It helps you:

Example:

npm install express

This adds Express as a dependency.

dependencies vs devDependencies

{
  "dependencies": {
    "express": "^4.18.2"
  },
  "devDependencies": {
    "vitest": "^2.0.0"
  }
}

dependencies are needed to run the app.

devDependencies are needed only during development, testing, or building.

Interview answer

Modules help organize Node.js code into reusable files. Node supports CommonJS with require/module.exports and ES Modules with import/export. npm is the package manager used to install dependencies, run scripts, and manage project packages through package.json.