Loading

T8 Node.js · Lesson 3

npm and packages

Most of a program is code that someone else has already written and shared. npm is how Node programmers share it: a registry of packages, and the command that fetches them. Describe your project in package.json, start its jobs with npm run, add packages with npm install, choose their versions with care, and see how Node finds a package in node_modules.

  • say what a package, the npm registry and the npm command are
  • make a package.json with npm init, and read and change its fields
  • run a project's jobs with npm run, npm start and npm test
  • add a package with npm install, and say what node_modules and package-lock.json hold
  • read a version such as 2.1.3, and the ranges ^2.1.3 and ~2.1.3
  • say how require and import find a package, and look at it with npm ls
About 55 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-11-09); npm on the laptop, the one that ships with its Node 22.23.1 (the kit compares every npm block with it, in its sandbox, with no network) 10.9.8 (2026-11-09); GNU Bash on the laptop (the kit compares every shell block with it, in a sandbox) 5.3.9 (2026-11-09)Play this lesson's games

The back cover

Most of a program is code that someone else has already written and shared. npm is how Node programmers share it. It is a huge store of packages, and the command that fetches them into your project.

These pages show what a package is, and the package.json card that describes a project. They show scripts, the named jobs of a project. They show how npm install fetches packages and records their exact versions. They also show what version ranges mean, and how Node finds a package once it is installed.

Before you start

The story: Parts from other halls

The pump-house needs a timer that can read a time such as two hours. The fitters start to build one, and the Foreman stops them at the bench.

"The Clockmakers made a timer like that years ago," she says, "and so did the Bell-founders. Every hall in the city has made parts that we could use." She points to the far wall, where a long shelf holds crates from every hall, each with a label, a number and a list of what it needs.

"Take a part from the shelf, and write down which one and which edition, so that the next fitter gets the same. Then build only what nobody has built."

Lesson 02 split one program into modules of your own. Most real programs also use modules that other people wrote and shared: a package to read dates, one to talk to a database, one to build a web server. This lesson is about where those come from, how a project records which ones it uses, and how Node finds them.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
Modules.require("./gauge")A package is a module from elsewhere.
require without ./.require("fs")It also finds packages.
JSON.{ "name": "shop" }package.json is JSON.
"type": "module".package.jsonThe file that holds it.
Running a command.node app.jsnpm runs such commands by name.
Exit codes.echo $?A script's failure reaches npm.
Folders and paths.cd toolsnpm finds the project's folder.
.gitignore.node_modules/What a repository leaves out.
Versions.v22.23.1Every package has one.
The Archive's tags.v1.0A version names one state of the work.

By the end of this lesson you will be able to:

  • say what a package, the npm registry and the npm command are;
  • make a package.json with npm init, and read and change its fields;
  • run a project's jobs with npm run, npm start and npm test;
  • add a package with npm install, and say what node_modules and package-lock.json hold;
  • read a version such as 2.1.3, and the ranges ^2.1.3 and ~2.1.3;
  • say how require and import find a package, and look at it with npm ls.

How to follow this lesson

The blocks run the npm command on the page, except one: fetching a package from npm's registry needs the network, which the page cannot reach, so that session is shown as it was measured in a real terminal. The packages that the other blocks use are small ones of our own, laid out exactly as npm lays out a real one.

In one line

This lesson is about npm and packages: shared code, the project card package.json, scripts, installing, versions, and node_modules.

Packages and npm

At a glance

Nobody writes every part of a program alone. Most programs lean on code that others have written, tested and shared.

A package is a folder of shared code with a file named package.json that describes it. The name npm means three things. It is the registry, a huge database that holds packages; the website that searches it; and the command that uses it from a terminal. npm comes with Node, so if node --version works, npm is usually there too.

Take a guess: Who started npm, and who owns it now?

A package is a folder of code that someone has shared, with a file inside, package.json, that names it and gives its version. Some packages are tiny, a single function; some are whole frameworks. Either way, using one means that you do not write that part yourself.

npm is how Node programmers share packages. Its documentation describes three parts. The registry is a large public database of packages; its documentation calls it the world's largest software registry. The website, npmjs.com, is where you search it. The npm command, which came with Node when Node was installed, is how you use it from a terminal:

In the shop's folder, /home/asha/shop

node --version
npm --version
v22.23.1
10.9.8

The two have separate versions: Node 22 came with npm 10. The command npm works on the project in the folder where you type it, as git does in the Archive.

Part of npmWhat it isYou meet it as
the registrya public database of packagesthe place npm install fetches from
the websitea search and a page for each packagenpmjs.com
the commanda program in your terminalnpm init, npm run, npm install

A project that uses packages is itself a package: it has a package.json of its own, which lists the packages it needs. The rest of this lesson follows the life of that file.

Worked example 1

Before starting a project, check which versions of Node and npm the machine has, so that you can say which ones a lesson or a project was checked with.

What we have: a terminal

What we need: Node's version and npm's

The plan: each command answers --version

In the shop's folder, /home/asha/shop

node --version
npm --version
v22.23.1
10.9.8
  1. Node prints its version with a v in front; npm prints only the numbers.

Node 22.23.1, with npm 10.9.8.

Check: The lesson's own label says the same: checked with Node 22.23.1 and npm 10.9.8.

A path that fails: npm -version, with one dash. Short options take one dash and one letter, -v; long ones take two dashes, --version.

When you are stuck: you are not sure whether npm is installed

npm --version prints its version if it is.

npm comes with Node: if node --version works, npm is usually there too.

A message such as command not found means that Node, or its folder on PATH, is missing.

Your turn

What are the three parts of npm?Tap to reveal
  1. One is a database, one a website, one a command.

The registry, the website and the command.

What makes a folder a package?Tap to reveal
  1. Which file names it?

A package.json with its name and version.

npm --version
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
10.9.8
  1. The npm that came with Node 22.

It prints 10.9.8.

Did you know?

npm, also known as Isaac

npm's original author was Isaac Z. Schlueter, and its first release came on 12 January 2010. In a talk in 2018, Ryan Dahl, who created Node, gave npm much of the credit for Node's growth after he left. One slide says npm, also known as Isaac, decoupled the core Node library and allowed the ecosystem to be distributed: anyone could share a package without changing Node itself.

Why it fits here: It answers this topic's question: Isaac Z. Schlueter started npm in 2010, and Ryan Dahl credited it with spreading Node's ecosystem.

Sources: Wikipedia: npm; Ryan Dahl: Design Mistakes in Node (JSConf EU 2018)

npm joined GitHub in 2020

The registry has had a change of owner. On 16 March 2020, Nat Friedman, then GitHub's chief executive, announced that GitHub had signed an agreement to acquire npm, calling it a critical part of the JavaScript world. Wikipedia now lists npm, Inc. as a subsidiary of GitHub, which is itself a subsidiary of Microsoft.

Why it fits here: It completes this topic's npm: since 2020 the registry belongs to GitHub, and so to Microsoft.

Sources: GitHub Blog: npm is joining GitHub; Wikipedia: npm

In one line

A package is a folder of shared code with a package.json. npm is the registry that holds packages, the website that searches it, and the command that uses it from a terminal.

The project's card: package.json

At a glance

Every project carries a card that describes it, the way a book has a title page. In Node that card is package.json.

It holds the project's name and version, its main file, its scripts and the packages it depends on, all in JSON. The command npm init -y makes one with sensible defaults, without asking questions. The commands npm pkg get, npm pkg set and npm pkg delete read and change single fields, so you need not edit the JSON by hand.

Take a guess: Can a package name be as long as you like, with capital letters?

Every Node project keeps one file at its top, package.json: the card on the crate. It names the project, gives its version, and lists the jobs it can run and the packages it needs. The command npm init makes one; with -y it takes every default instead of asking:

In the shop's folder, /home/asha/shop

npm init -y
Wrote to /home/asha/shop/package.json:

{
  "name": "shop",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}


The name comes from the folder, shop. The version starts at 1.0.0. The other fields wait to be filled in. The file is plain JSON, so you can read it with cat and change it in any editor.

FieldHolds
"name"the package's name: small letters, no spaces
"version"its version, as MAJOR.MINOR.PATCH (a later section)
"main"the file that require gives when someone requires the package
"scripts"the project's jobs, each a name and a command
"dependencies"the packages it needs, each with a range of versions
"type"module, to make its .js files ES modules (lesson 02)

Reading and changing it with npm pkg

In a terminal with no editor, npm pkg reads and changes fields for you. get prints a field's value as JSON; set gives fields new values; delete removes them:

In the shop's folder, /home/asha/shop

npm init -y > /dev/null
npm pkg set description="The pump-house engine" type=module
npm pkg get name version description type
{
  "name": "shop",
  "version": "1.0.0",
  "description": "The pump-house engine",
  "type": "module"
}

> /dev/null hid the long output of npm init. Asked for one field, npm pkg get prints that value alone, as a JSON string:

In the shop's folder, /home/asha/shop

npm init -y > /dev/null
npm pkg get name
"shop"

Worked example 2

Start a project in a new folder called pump house, and check the name that npm gives it.

What we have: a folder name with a space and capital letters, Pump House

What we need: the package name in package.json

The plan: mkdir and cd; npm init -y; npm pkg get name

In the shop's folder, /home/asha/shop

mkdir "Pump House"
cd "Pump House"
npm init -y > /dev/null
npm pkg get name
"pump-house"
  1. A package name has small letters and no spaces, so npm made pump-house from the folder's name.

The project is named pump-house.

Check: npm pkg get version prints "1.0.0".

A path that fails: writing package.json by hand with "name": "Pump House". Package names may not have capital letters or spaces, and the registry would refuse it.

When you are stuck: npm says it cannot read package.json

Look for the file with ls: npm works on the project in the folder where you are, or the nearest folder above it with a package.json.

If there is none, make one with npm init -y.

If there is one, check that it is valid JSON: a missing comma or quote breaks it.

Your turn

Which command makes a package.json without asking any questions?Tap to reveal
  1. init, with one option.

npm init -y.

Which field lists the project's jobs?Tap to reveal
  1. Each job has a name and a command.

"scripts".

npm init -y > /dev/null
npm pkg get version
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
"1.0.0"
  1. npm init starts every project at 1.0.0.
  2. npm pkg get prints the value as JSON.

It prints "1.0.0".

Did you know?

214 characters, all small letters

A package name has rules. npm's documentation for package.json says a name must be 214 characters or fewer, the scope included, and that new packages must not have capital letters in their names. The reason it gives: the name becomes part of a web address, an argument on the command line and a folder name, so it cannot hold characters that are unsafe in addresses.

Why it fits here: It answers this topic's question: a package name has at most 214 characters and no capital letters.

Source: npm Docs: package.json

A field that stops publishing

One field protects a project from being shared by accident. npm's documentation says that if package.json holds "private": true, npm will refuse to publish it. It calls this a way to prevent the accidental publication of private repositories. Most app projects, as opposed to libraries meant for others, set it at once.

Why it fits here: It adds a safety field to this topic's package.json: "private": true makes npm refuse to publish the project.

Source: npm Docs: package.json

In one line

package.json is a project's card: its name, version, main file, scripts and dependencies. npm init -y makes one; npm pkg get, set and delete read and change its fields.

A project's jobs: scripts

At a glance

Every project has jobs that are run again and again: start the program, run the tests, build the files. Scripts give each job a short name.

Scripts live in package.json, under a name each. The commands npm start and npm test run those two scripts, and npm run with a name runs any other. Each script runs in the project's folder, wherever you typed the command. Its exit code becomes npm's, so a failing test makes npm fail too, as it should.

Take a guess: How can a script call a tool installed in node_modules without its full path?

A project has jobs that people run again and again: start the program, run its tests, build it. package.json keeps each as a script: a name, and the command that does the job. Then anyone can start the job by its name, without knowing the command. A start script is the usual first one:

app.js

console.log("engine started");

Terminal: npm pkg set scripts.start="node app.js" npm start


> shop@1.0.0 start
> node app.js

engine started

Before it runs the command, npm prints two lines: the project, shop@1.0.0, with the script's name, and the command itself. Then the program's own output follows. npm start runs the start script; npm test runs test. Every other script runs with npm run and its name.

The test script that npm init made

In the shop's folder, /home/asha/shop

npm init -y > /dev/null
npm test
echo "[$?]"

> shop@1.0.0 test
> echo "Error: no test specified" && exit 1

Error: no test specified
[1]

The default test only says that there are no tests, and fails with the exit code 1, so that nobody mistakes it for a passing test. A script's exit code becomes npm's: tools that run npm test, such as the checks of a later step, see the failure.

Listing and running any script

npm run with no name lists the scripts. The ones npm knows by name, such as test and start, come first:

In the shop's folder, /home/asha/shop

npm init -y > /dev/null
npm pkg set scripts.start="node app.js" scripts.greet="echo Good morning"
npm run
Lifecycle scripts included in shop@1.0.0:
  test
    echo "Error: no test specified" && exit 1
  start
    node app.js
available via `npm run-script`:
  greet
    echo Good morning

Words after -- are added to the end of the command, and --silent leaves out npm's two lines:

In the shop's folder, /home/asha/shop

npm init -y > /dev/null
npm pkg set scripts.greet="echo Good morning"
npm run greet -- Asha
npm run greet --silent

> shop@1.0.0 greet
> echo Good morning Asha

Good morning Asha
Good morning

A script always runs in the project's own folder, the one with package.json, even when you type npm run in a folder below it:

In the shop's folder, /home/asha/shop

npm init -y > /dev/null
npm pkg set scripts.where=pwd
mkdir -p tools
cd tools
npm run where

> shop@1.0.0 where
> pwd

/home/asha/shop
CommandRuns
npm startthe start script
npm test, npm tthe test script
npm run nameany script, by its name
npm runnothing: it lists the scripts
npm run name -- wordsthe script, with words added to its command

Worked example 3

The pump-house needs a check job that runs check.js and fails when the pressure is too high, so that npm run check can stop a start.

What we have: check.js, which sets process.exitCode to 1 above a pressure of 3

What we need: a check script whose failure reaches the shell

The plan: npm pkg set scripts.check="node check.js"; run it, then print $?

check.js

const pressure = 4;
if (pressure > 3) {
  console.error("pressure too high:", pressure);
  process.exitCode = 1;
}

Terminal: npm pkg set scripts.check="node check.js" npm run check --silent echo "[$?]"

pressure too high: 4
[1]
  1. The program's exit code became npm's, so npm run check && npm start would never start a pump-house at the wrong pressure.

npm run check fails with 1, as check.js does.

Check: Set the pressure to 2: the script prints nothing and exits with 0.

A path that fails: a check script that only prints a warning with console.log. It would exit with 0, and npm run check && npm start would start anyway.

When you are stuck: npm run says Missing script

npm run, with no name, lists the scripts this package.json has.

Check the spelling, and that you are in the right project: npm uses the nearest package.json above you.

Add the script with npm pkg set scripts.name="command".

Your turn

Which command runs the script called build?Tap to reveal
  1. build is not one of npm's lifecycle names.

npm run build.

What does --silent leave out?Tap to reveal
  1. npm prints two lines before the command.

npm's two lines: the project and the command.

npm init -y > /dev/null
npm pkg set scripts.hi="echo hi"
npm run hi --silent
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
hi
  1. --silent leaves out npm's lines.
  2. Only the command's output remains.

It prints hi.

Did you know?

node_modules/.bin joins the PATH

Scripts can name tools that are installed only in your project. npm's documentation says that in addition to the shell's existing PATH, npm run adds node_modules/.bin to the PATH given to scripts. So a tool that a dependency installs there can be called by its bare name inside a script, without writing node_modules/.bin in front.

Why it fits here: It answers this topic's question: npm run puts node_modules/.bin on the PATH, so scripts can call local tools by name.

Source: npm Docs: npm run

Scripts that run before and after

A script can have helpers that run around it. npm's documentation says that adding pre or post to the front of a script's name makes another script that runs before or after it. Its example has precompress, compress and postcompress: npm run compress then runs all three, in that order.

Why it fits here: It adds to this topic's scripts: a pre or post script runs by itself before or after the script of the same name.

Source: npm Docs: Scripts

In one line

Scripts are a project's jobs, kept in package.json by name. npm start and npm test run those two; npm run name runs any other; the script runs in the project's folder, and its exit code is npm's.

Installing a package: npm install

At a glance

Using someone's package starts with fetching it. npm does the fetching, and keeps a record of exactly what it fetched.

The command npm install with a package's name puts the package in node_modules, adds it to the dependencies in package.json, and writes its exact version into package-lock.json. The command npm install alone rebuilds node_modules from those two files. That is why node_modules stays out of git: anyone can rebuild it exactly. Run npm install with no name right after cloning a project.

Take a guess: What happened when a package called left-pad vanished from npm in 2016?

The command npm install fetches a package from the registry and adds it to the project. Its name follows the command. Here a project takes ms, a small package that turns a time written as text, such as 2h for two hours, into milliseconds:

Measured in a real terminal on 2026-11-09, with Node 22.23.1 and npm 10.9.8 (the time, 546ms, changes from run to run)

asha@tower:~/shop$ npm install ms

added 1 package, and audited 2 packages in 546ms

found 0 vulnerabilities

This one session is shown as it was measured, not run: the page cannot reach the registry. The command added one package, ms. It also checked the project's two packages, the project and ms, against a list of known security problems, and found 0 vulnerabilities. Three things in the folder changed.

What the install changed

First, package.json. npm added the package to its dependencies, with a range of versions, which the next section explains:

package.json, after npm install ms

{
  "name": "shop",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ms": "^2.1.3"
  }
}

Second, node_modules. The package's files now sit in a folder node_modules/ms, inside the project. Every package the project installs goes into node_modules, with the packages that those packages need.

Third, package-lock.json. npm wrote down the exact version it chose, 2.1.3, where it came from, and a checksum of the file, called integrity:

package-lock.json, after npm install ms

{
  "name": "shop",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "shop",
      "version": "1.0.0",
      "license": "ISC",
      "dependencies": {
        "ms": "^2.1.3"
      }
    },
    "node_modules/ms": {
      "version": "2.1.3",
      "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
      "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
      "license": "MIT"
    }
  }
}

package.json says which versions the project accepts; package-lock.json says which one it got. npm's documentation says that when a package-lock.json is present, it drives the installation, so everyone who installs the project gets the same versions.

Installing a project that someone else made

Run with no package name, npm install reads package.json and package-lock.json and fetches every package they list into node_modules. That is the first command after cloning a project from GitHub. So node_modules never goes into the repository: it is large, and npm can rebuild it from the two files. The Archive's .gitignore keeps it out:

In a project with a package.json and a node_modules folder

printf 'node_modules/\n' > .gitignore
git init -q
git add .
git status -s
A  .gitignore
A  package.json
CommandWhat it does
npm install namefetches a package, adds it to dependencies and package-lock.json
npm installfetches every package that package.json and the lock list
npm install -D namethe same, into devDependencies: tools used only while building
npm uninstall nameremoves a package from node_modules and package.json

Worked example 4

A fitter clones the pump-house project. Its repository has package.json and package-lock.json, but no node_modules. What must they run before npm start, and what will they get?

What we have: package.json and package-lock.json, listing ms at 2.1.3

What we need: the same packages the project's author had

The plan: npm install with no name reads both files and fetches what they list

  1. They run npm install, with no name. npm reads package.json, sees ms, and follows package-lock.json to the exact version 2.1.3, so the fitter gets the very crate that the author had. Then npm start works.

npm install, which brings ms 2.1.3, as the lock says.

Check: npm ls afterwards lists ms@2.1.3.

A path that fails: copying the author's node_modules folder by hand. It is large, may hold files built for another computer, and npm install rebuilds it exactly from the two files anyway.

When you are stuck: a project from GitHub says Cannot find module

Look for node_modules: a fresh clone has none.

Run npm install, with no name, in the folder with package.json.

Then run the program again.

Your turn

Which three things change when you run npm install ms?Tap to reveal
  1. One file gains a line; one folder appears; one file records exact versions.

package.json, node_modules and package-lock.json.

Why does node_modules belong in .gitignore?Tap to reveal
  1. Can npm rebuild it?

npm install rebuilds it from package.json and package-lock.json.

What is the difference between dependencies and devDependencies?Tap to reveal
  1. Which ones does the program need when it runs?

dependencies are needed to run; devDependencies only while building, such as test tools.

Did you know?

The day left-pad vanished

In March 2016 a dispute over a package name broke many builds at once. npm's own account says that an author unpublished the package kik and 272 other packages without warning, and one of them was left-pad. Shortly after 2:30 in the afternoon, Pacific time, on Tuesday 22 March, npm saw hundreds of failures per minute, and many thousands of projects were affected.

Why it fits here: It answers this topic's question: when left-pad was unpublished in 2016, many thousands of projects that depended on it failed to install.

Source: npm Blog: kik, left-pad, and npm

npm ci, the strict install

npm has a stricter install for machines that build and test code. Its documentation says npm ci is meant for automated places such as test platforms, continuous integration and deployment. If the lock file and package.json disagree, npm ci stops with an error instead of updating the lock. It removes any existing node_modules first, and never writes to package.json or the lock: installs are frozen.

Why it fits here: It adds to this topic's lock file: npm ci installs exactly what the lock says, or stops.

Source: npm Docs: npm ci

In one line

npm install name fetches a package into node_modules, adds it to package.json's dependencies, and writes the exact version to package-lock.json. npm install alone rebuilds node_modules from those files, so node_modules stays out of git.

Versions and ranges

At a glance

A package keeps changing after you install it: fixes, new features, and now and then a change that breaks old code. Its version number says which kind each release is.

A version is MAJOR.MINOR.PATCH: breaking changes, new features, fixes. In package.json, ^2.1.3 accepts newer minor and patch releases of 2, ~2.1.3 accepts newer patches of 2.1, and 2.1.3 alone accepts that version only. The lock file then pins the exact version actually installed. Reading those two signs is a daily skill.

Take a guess: Why does npm write ^ in front of a version you install?

Every package version has three numbers, such as 2.1.3: MAJOR.MINOR.PATCH. Their meaning is a promise, called semantic versioning, and npm's documentation spells it out. A bug fix that changes nothing else raises the last number. A new feature that breaks nothing raises the middle one. A change that breaks code written for the old version raises the first one.

The changeKind of releaseFrom 2.1.3 to
a bug fix, nothing elsepatch2.1.4
a new feature, nothing brokenminor2.2.0
a change that can break your codemajor3.0.0

A dependency in package.json gives a range: which versions the project accepts. npm install ms wrote ^2.1.3. The caret, ^, accepts newer minor and patch releases, never a new major one. The tilde, ~, is stricter: newer patch releases only. A version with neither accepts that version alone.

RangeAcceptsRefuses
^2.1.32.1.3, 2.1.9, 2.4.03.0.0, and anything below 2.1.3
~2.1.32.1.3, 2.1.92.2.0, 3.0.0
2.1.32.1.3 onlyeverything else

Here is the rule as a small program of our own, to try ranges for yourself. It handles the two common forms, for versions from 1.0.0 up:

check.js

function allows(range, version) {
  const [major, minor, patch] = range.slice(1).split(".").map(Number);
  const [a, b, c] = version.split(".").map(Number);
  if (range[0] === "^") return a === major && (b > minor || (b === minor && c >= patch));
  if (range[0] === "~") return a === major && b === minor && c >= patch;
  return false;
}
for (const v of ["2.1.3", "2.1.9", "2.4.0", "3.0.0"]) {
  console.log(v, allows("^2.1.3", v), allows("~2.1.3", v));
}

Terminal: node check.js

2.1.3 true true
2.1.9 true true
2.4.0 true false
3.0.0 false false

So npm install, run again next month, may bring 2.1.9 under ^2.1.3: a fix, by the promise, that the project wants. It will never bring 3.0.0, which might break it. The lock file keeps even that choice fixed until someone asks for newer versions.

Below 1.0.0

A package whose first number is 0 is still settling, and every new minor release may break things. npm's caret is stricter there: ^0.2.3 accepts 0.2.x only. The program above leaves that case out.

Worked example 5

The pump-house depends on gauge-kit ^1.4.0. The registry has 1.4.2, 1.9.0 and 2.0.0. Which may npm install, and why?

What we have: the range ^1.4.0 and three versions

What we need: the versions the range accepts

The plan: ^ keeps the first number and accepts anything from 1.4.0 up within it; check each with the program

check.js

function allows(range, version) {
  const [major, minor, patch] = range.slice(1).split(".").map(Number);
  const [a, b, c] = version.split(".").map(Number);
  if (range[0] === "^") return a === major && (b > minor || (b === minor && c >= patch));
  if (range[0] === "~") return a === major && b === minor && c >= patch;
  return false;
}
for (const v of ["1.4.2", "1.9.0", "2.0.0"]) console.log(v, allows("^1.4.0", v));

Terminal: node check.js

1.4.2 true
1.9.0 true
2.0.0 false
  1. 1.4.2 is a patch and 1.9.0 a minor release of the same major version, so both keep the promise. 2.0.0 is a new major version, which may break the pump-house.

1.4.2 and 1.9.0, never 2.0.0; npm takes the newest, 1.9.0.

Check: With ~1.4.0, only 1.4.2 would do.

A path that fails: reading ^1.4.0 as 1.4.0 or more, with no limit. The caret never crosses to the next major version.

When you are stuck: a package changed between two installs

Read its range in package.json: ^ allows new minor releases.

Keep package-lock.json in git, so that npm install gives everyone the version it records.

To hold one version exactly, write it without ^ or ~.

Your turn

A package goes from 4.2.7 to 4.3.0. What kind of release is it, and should it break your code?Tap to reveal
  1. Which number rose?

A minor release: new features, and it should not break your code.

Does ~3.1.0 accept 3.2.0?Tap to reveal
  1. The tilde takes patch releases only.

No.

node -p '"2.1.3".split(".").map(Number)'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
[ 2, 1, 3 ]
  1. split cuts the text at each dot.
  2. Number turns each part into a number.

It prints [ 2, 1, 3 ].

Did you know?

Why the caret appears

npm writes the caret for you. Its documentation says the setting save-prefix, whose default is ^, decides how a version installed into package.json is written. So installing version 1.2.3 records ^1.2.3, which allows minor upgrades. After npm config set save-prefix='~', the same install records ~1.2.3, which allows only patch upgrades.

Why it fits here: It answers this topic's question: npm's save-prefix setting, ^ by default, puts the caret in front.

Source: npm Docs: Config

x, X and * as wild cards

Ranges can also be written with wild cards. npm's semver documentation describes X-ranges, where x, X or * stands in for one of the three numbers. So 1.2.x accepts any patch of 1.2, and 1.x means at least 1.0.0 but below 2.0.0. A lone * accepts any version that is not a pre-release, which is rarely a wise choice for a real project.

Why it fits here: It adds to this topic's ranges: 1.2.x and 1.x are wild-card ranges, and * accepts almost any version.

Source: npm: node-semver

In one line

A version is MAJOR.MINOR.PATCH: breaking changes, new features, fixes. In package.json, ^2.1.3 accepts newer minor and patch releases of 2, ~2.1.3 newer patches of 2.1, and 2.1.3 that version only.

How Node finds a package

At a glance

Once a package sits in node_modules, require and import can reach it by its name alone, with no path.

Node looks for the name in a node_modules folder next to the calling file, then in the parent folder's node_modules, and so on up to the root. In the package's folder it loads what the exports field offers, or else its main file, or else index.js. The command npm ls shows what is installed, and marks anything package.json does not list.

Take a guess: Can require find a package installed with npm install -g?

A package is required by its name alone, with no ./ in front. Node then looks in a folder called node_modules, in the caller's folder; if the package is not there, in the node_modules of the folder above, and so on up to /. In the package's folder, package.json's main names the file to load:

node_modules/gauge-kit/package.json

{
  "name": "gauge-kit",
  "version": "1.2.0",
  "main": "lib/gauge.js"
}

node_modules/gauge-kit/lib/gauge.js

exports.read = (name) => `${name}: 95`;

app.js

const gauge = require("gauge-kit");
console.log(gauge.read("boiler"));

Terminal: node app.js

boiler: 95

Here gauge-kit is a small package of our own, put in node_modules by hand. A package that npm installs sits there in exactly the same way. Because Node looks upward, a file in a subfolder finds the same package:

node_modules/gauge-kit/package.json

{
  "name": "gauge-kit",
  "version": "1.2.0",
  "main": "lib/gauge.js"
}

node_modules/gauge-kit/lib/gauge.js

exports.read = (name) => `${name}: 95`;

tools/report.js

console.log(require("gauge-kit").read("pump"));

Terminal: node tools/report.js

pump: 95

exports: what a package offers

A newer package lists its entry points in an exports field, which npm's documentation calls a modern alternative to main. exports can offer a different file to require and to import, and nothing that it does not list:

node_modules/valve-kit/package.json

{
  "name": "valve-kit",
  "version": "2.0.1",
  "exports": {
    ".": { "import": "./valve.mjs", "require": "./valve.cjs" }
  }
}

node_modules/valve-kit/valve.mjs

export const kind = "the ES module valve";

node_modules/valve-kit/valve.cjs

exports.kind = "the CommonJS valve";

app.mjs

import { kind } from "valve-kit";
console.log(kind);

Terminal: cat > app.js <<'END' console.log(require("valve-kit").kind); END node app.mjs node app.js

the ES module valve
the CommonJS valve

import took the file named under import, and require the one under require. A file inside the package that exports does not offer cannot be reached, even though it is there:

node_modules/valve-kit/package.json

{
  "name": "valve-kit",
  "version": "2.0.1",
  "exports": {
    ".": { "import": "./valve.mjs", "require": "./valve.cjs" }
  }
}

node_modules/valve-kit/valve.mjs

export const kind = "the ES module valve";

node_modules/valve-kit/valve.cjs

exports.kind = "the CommonJS valve";

app.js

try {
  require("valve-kit/valve.cjs");
} catch (e) {
  console.log(e.code);
  console.log(e.message);
}

Terminal: node app.js

ERR_PACKAGE_PATH_NOT_EXPORTED
Package subpath './valve.cjs' is not defined by "exports" in /home/asha/shop/node_modules/valve-kit/package.json

Looking at what is installed: npm ls

npm ls draws the project and the packages in its node_modules. A package that package.json does not list is called extraneous, a sign that someone put it there without npm install. Here gauge-kit was put into node_modules after npm init -y had made package.json:

In the shop's folder, with a package.json, and gauge-kit put into node_modules after it

npm ls
npm pkg set dependencies.gauge-kit="^1.2.0"
npm ls
shop@1.0.0 /home/asha/shop
└── gauge-kit@1.2.0 extraneous

shop@1.0.0 /home/asha/shop
└── gauge-kit@1.2.0

Once package.json lists it, npm ls draws it as an ordinary dependency. The other way round also works: npm init -y, run in a folder that already has a node_modules, lists every package it finds there as a dependency, with a caret in front of its version.

require("name") or import ... from "name"Node looks
a built-in, such as fsin Node itself, first
any other namein node_modules/name, from the caller's folder up to /
in the packageexports, for require or import; else main; else index.js
"name/path"that file in the package, if exports offers it

Worked example 6

A program in tools/ must use gauge-kit, which is installed in the project's top folder. Will require("gauge-kit") find it, and why?

What we have: node_modules/gauge-kit at /home/asha/shop, and tools/report.js

What we need: whether require finds the package

The plan: Node looks in node_modules from the caller's folder upward

node_modules/gauge-kit/package.json

{
  "name": "gauge-kit",
  "version": "1.2.0",
  "main": "lib/gauge.js"
}

node_modules/gauge-kit/lib/gauge.js

exports.read = (name) => `${name}: 95`;

tools/report.js

console.log(require("gauge-kit").read("press"));

Terminal: node tools/report.js

press: 95
  1. Node looked in /home/asha/shop/tools/node_modules, found nothing, went up one folder, and found /home/asha/shop/node_modules/gauge-kit.

Yes: the search goes up from tools/ to the project's node_modules.

Check: A program in /home/asha, above the project, would not find it: the search goes up, never down.

A path that fails: require("./node_modules/gauge-kit") from tools/. That path starts in tools/, so it looks for tools/node_modules/gauge-kit, and fails.

When you are stuck: Node says Cannot find module or Cannot find package for a package

Check that it is installed: npm ls lists node_modules, or ls node_modules.

Check the folder: Node searches from the file's folder upward, never into other branches.

For a path inside a package, check that its exports offers that path.

Your turn

app.js in /home/asha/shop/tools requires gauge-kit. Name the first two folders where Node looks.Tap to reveal
  1. It starts in the caller's folder.

/home/asha/shop/tools/node_modules, then /home/asha/shop/node_modules.

What does extraneous mean in npm ls?Tap to reveal
  1. Is the package in package.json?

The package is in node_modules but not listed in package.json.

A package's exports lists only ".". Can require("pkg/lib/x.js") reach that file?Tap to reveal
  1. exports offers only what it lists.

No: ERR_PACKAGE_PATH_NOT_EXPORTED.

Did you know?

Global packages are not for require

A package installed with npm install -g is not where require looks. npm's documentation says global installs on Unix go to the prefix folder's lib/node_modules. The Node manual explains that require searches global folders only through the NODE_PATH setting and a few old folders, which it calls mostly historic. It strongly encourages dependencies in the local node_modules, which load faster and more reliably.

Why it fits here: It answers this topic's question: require does not search npm's global folder, so dependencies belong in the local node_modules.

Sources: npm Docs: Folders; Node.js manual: Modules (CommonJS)

NODE_PATH, a PATH for modules

Node has a setting that works like the shell's PATH, but for modules. The Node manual says that if NODE_PATH holds a list of absolute paths, separated by colons, Node searches them for modules it has not found elsewhere. On Windows the list is separated by semicolons. Like PATH, it is read from the environment, so it can be set for one command.

Why it fits here: It links this topic's search to the Linux track's PATH: NODE_PATH is a colon-separated list of extra folders for modules.

Source: Node.js manual: Modules (CommonJS)

In one line

require and import find a package by name in node_modules, from the caller's folder up to /, then load what its exports offers (or its main, or index.js). npm ls shows what is installed, and marks what package.json does not list.

Where it is used

Almost every Node project in the world starts with npm init and grows with npm install. Here is where each idea of this lesson does its work.

What you learnedWhere it is usedA real example
packages from the registryevery project that reuses others' worka web framework, a database client, a date library
package.jsonthe top of every Node projectthe first file to read in a project you join
scriptsthe same jobs for everyonenpm test in an automatic check, npm start on a server
package-lock.jsonthe same versions on every machinea server that installs exactly what the developers tested
semantic versioningtaking fixes, but not breaking changes^4.18.0 for a framework at version 4
node_modules and .gitignorerepositories that stay smallnpm install as the first command after git clone

The Foreman's shelf is the registry, each crate's label is its package.json, and the card that lists a project's crates with their editions is package.json with package-lock.json beside it.

Mistakes and debugging

These are the slips that people meet most often with npm. Every output below is the real one, from the code shown.

1. A script that is not there

In the shop's folder, /home/asha/shop

npm init -y > /dev/null
npm run build
echo "[$?]"
npm error Missing script: "build"
npm error
npm error To see a list of scripts, run:
npm error   npm run
npm error A complete log of this run can be found in: /home/asha/.npm/_logs/2026-01-01T10_00_00_000Z-debug-0.log
[1]

The fix: npm run, with no name, lists the scripts; add the missing one with npm pkg set scripts.build="...". The log's name holds the real date and time; here it is shown as the kit fixes it.

2. npm in a folder with no package.json

In the shop's folder, /home/asha/shop

npm run start
echo "[$?]"
npm error code ENOENT
npm error syscall open
npm error path /home/asha/shop/package.json
npm error errno -2
npm error enoent Could not read package.json: Error: ENOENT: no such file or directory, open '/home/asha/shop/package.json'
npm error enoent This is related to npm not being able to find a file.
npm error enoent
npm error A complete log of this run can be found in: /home/asha/.npm/_logs/2026-01-01T10_00_00_000Z-debug-0.log
[254]

The fix: cd into the project's folder, or make the project with npm init -y.

3. A package that is not installed

app.js

try {
  require("ms");
} catch (e) {
  console.log(e.code);
}

Terminal: node app.js

MODULE_NOT_FOUND

Common after git clone, which brings no node_modules. The fix: npm install, in the project's folder.

4. Committing node_modules

In a project with a package.json and a node_modules folder, and no .gitignore

git init -q
git add .
git status -s
A  node_modules/ms/package.json
A  package.json

A real node_modules holds thousands of files. The fix: put node_modules/ in .gitignore before the first commit, and git rm -r --cached node_modules if it already went in.

5. A package nobody listed

In the shop's folder, with a package.json, and gauge-kit put into node_modules by hand after it

npm ls
shop@1.0.0 /home/asha/shop
└── gauge-kit@1.2.0 extraneous

The program works today, but the next npm install on another machine will not bring gauge-kit, as package.json does not list it. The fix: install packages with npm install, which lists them.

The debugging corner: what does this project use?

npm pkg get dependencies shows what package.json asks for, npm ls shows what node_modules really holds, and package-lock.json shows the exact versions. When the three disagree, npm install brings node_modules back in line with the other two.

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

node_modules/gauge-kit/package.json

{
  "name": "gauge-kit",
  "version": "1.2.0",
  "main": "lib/gauge.js"
}

node_modules/gauge-kit/lib/gauge.js

exports.read = (name) => `${name}: 95`;

app.js

const gauge = require("gauge-kit");     // a package, found in node_modules
console.log(gauge.read("boiler"));

Terminal: npm init -y > /dev/null # package.json: the project's card npm pkg set scripts.start="node app.js" # a job, by name npm ls # what is installed npm start --silent

shop@1.0.0 /home/asha/shop
└── gauge-kit@1.2.0

boiler: 95
When you seeIt meansDo
Missing script: "x"package.json has no such scriptnpm run to list them
Could not read package.jsonno project herecd to it, or npm init -y
Cannot find module 'x'the package is not installednpm install
extraneous in npm lsin node_modules, not in package.jsonnpm install x, to list it
^2.1.32.1.3 or a newer 2.xnothing: fixes arrive, breaking changes do not
node_modules in git statusit is about to be committedadd node_modules/ to .gitignore

The story: A shelf of parts

You learn the shelf's ways. There is the card on each project that lists its name, its edition and its orders, and the jobs that the card can start by name. And there is the way to take a crate, check its number and keep it by your bench.

The timer comes from the Clockmakers' crate, edition 2.1.3. The pump-house card lists it, so any fitter who builds the pump-house again gets the very same crate.

The Foreman nods at the card. "Next," she says, "the files the engine reads and writes."

Reagents gathered: package, npm, package.json, dependency, node_modules, semantic versioning.

Sources

  • npm Docs (Documentation CC BY 4.0, code MIT (the npm/documentation repository's README, read 2026-11-08); reused with credit)
  • The Node.js documentation (Not stated for the docs in the Node.js LICENSE file (read 2026-10-26); facts and ideas only)