Modules and npm

Site Admin · 11 Sep 2026 · 9 views

Modules and npm

Modules split code into reusable files, and npm shares those modules across the ecosystem. Together they are how Node projects stay organized.

Exporting and importing

One file exports values, another imports them. CommonJS uses require and module.exports:

// math.js
module.exports = { add: (a, b) => a + b };
// app.js
const { add } = require('./math');
console.log(add(2, 3));

Modern Node also supports ES modules with import and export when the package type is module.

What npm does

npm installs packages, manages versions, and records dependencies. Initialize a project first:

npm init -y

This creates package.json, the manifest holding metadata, scripts, and dependencies.

Installing packages

Save a runtime dependency with:

npm install express

Development tools use the dev flag:

npm install --save-dev nodemon

node_modules holds the installed code, and package-lock.json pins exact versions for reproducible installs.

Scripts

Scripts give short aliases for commands:

// package.json
"scripts": {
  "start": "node src/index.js",
  "dev": "nodemon src/index.js"
}

Run them with npm start or npm run dev.

Global vs. local

Local installs stay inside the project and are preferred. Global installs via -g put tools on your PATH for command-line utilities.

Key Points

  • The module system shares code between files.
  • package.json records metadata and dependencies.
  • npm install adds packages to node_modules.
  • Scripts shorten common commands.
  • Prefer local installs over global ones.
Share this post:

Comments (0)

Please login or register to comment.