Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 133 ยท Modules and Packages

package.json and the npm Registry

Learn package.json for Node.js - name, version, type, exports, imports, scripts, dependencies, semver ranges, lockfiles, npm install and ci, npx and workspaces, with runnable stand-ins.

Every Node.js project has a file called package.json at its root. It is the project's identity card and instruction manual: the name and version, what the code needs, which commands you can run, and how other code should load it. npm (the Node Package Manager) reads that file to install dependencies, and Node itself reads it to decide whether .js files are ES modules or CommonJS.

The npm registry is the public warehouse of packages (over two million of them), and the npm command-line tool, which ships with Node, downloads from it. Other tools such as pnpm and Yarn read the same package.json.

Our editor has no internet access and no npm packages installed, and you cannot run npm in it. Commands like npm install are shown as read-only code, labelled as "what you would type on your machine". The package.json concepts themselves, parsing, version ranges and script running, are things we can build and run right here.

Creating a package.json

On your machine, npm init -y creates one with defaults. Here is a typical modern file, annotated field by field.

JSON
{
  "name": "weather-cli",
  "version": "1.4.2",
  "description": "Print the weather for a city",
  "type": "module",
  "main": "./src/index.js",
  "exports": {
    ".": "./src/index.js",
    "./package.json": "./package.json"
  },
  "bin": { "weather": "./bin/weather.js" },
  "scripts": {
    "start": "node src/index.js",
    "test": "node --test",
    "lint": "eslint ."
  },
  "dependencies": { "chalk": "^5.4.0" },
  "devDependencies": { "eslint": "^9.0.0" },
  "engines": { "node": ">=22" },
  "license": "MIT"
}

Because the file is plain JSON, you can read and write it with the tools you already know. This program creates one and then reads it back the way tools do.

Node.js Reading a package.json

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

JSON has no comments and no trailing commas; a single stray comma makes npm refuse to run. Use npm pkg get name and npm pkg set version=2.0.0 to read or change fields from the command line.

The important fields

Field Purpose
name Lowercase, no spaces; may be scoped like @acme/tools. Required to publish.
version A semantic version, MAJOR.MINOR.PATCH. Required to publish.
type "module" or "commonjs" (default). Decides how .js files load, see ES Modules.
main The entry file for old tooling and require().
exports The modern, strict entry map; hides everything it does not list.
imports Private aliases that start with #, usable only inside this package.
bin Command names that become executables when the package is installed.
scripts Named commands you run with npm run.
dependencies Packages needed at runtime.
devDependencies Packages needed only for development (tests, linters, build tools).
peerDependencies Packages that the user must provide, common in plugins.
optionalDependencies Dependencies that may fail to install without breaking the install.
engines Node and npm versions the package supports. Advisory unless engine-strict is set.
files Which files go into the published tarball.
private true prevents accidental publishing.
workspaces Folders of sub-packages in a monorepo.

The imports field: private aliases

Long relative paths such as ../../../utils/format.js are fragile. The imports field lets a package define aliases beginning with #. They only resolve for files inside the package that declares them, and they work without a bundler.

Node.js Subpath imports with #

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first alias maps one name to one file, and the second uses a * pattern to map a whole folder. Notice that main.mjs found the package.json in its own folder: Node looks for the nearest package.json, walking up from the importing file.

Semantic versioning

Every package version has three numbers, MAJOR.MINOR.PATCH, and the convention (semver) gives each a meaning:

  • PATCH (1.4.2): bug fixes only; safe to take.
  • MINOR (1.4.2): new features that stay backwards compatible.
  • MAJOR (1.4.2): breaking changes. Read the changelog.

In dependencies you write a range, not just a number. The two you will see constantly are:

Range Means Matches
^1.4.2 (caret) Same major version, at least 1.4.2 1.4.2, 1.9.0; not 2.0.0
~1.4.2 (tilde) Same minor version, at least 1.4.2 1.4.2, 1.4.9; not 1.5.0
1.4.2 Exactly that version only 1.4.2
>=1.4.0 <2 A custom range 1.4.0 up to 1.x
* or latest Anything everything (avoid)

For 0.x versions the caret is stricter: ^0.2.3 allows only 0.2.x, because anything below 1.0 is considered unstable. Real npm uses a library called semver; the idea is small enough to build in a few lines, which teaches you exactly what the symbols do.

Node.js A tiny semver matcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last two lines show why versions must be compared numerically: sorted as plain strings, 1.10.0 lands before 1.2.0. The real semver package also handles pre-release tags (2.0.0-beta.1) and build metadata, which this stand-in ignores.

Installing and the lockfile

On your own machine you add and remove packages with commands (read-only here, what you would type):

Terminal
npm install express            # add to dependencies and download it
npm install --save-dev eslint  # add to devDependencies
npm install                    # install everything listed in package.json
npm ci                         # clean, exact install from the lockfile (for CI and deploys)
npm uninstall express
npm update                     # move within the allowed ranges
npm outdated                   # show packages with newer versions
npm audit                      # check dependencies for known vulnerabilities

npm install downloads each package, plus its dependencies, plus theirs, into a node_modules folder, and writes a package-lock.json. The lockfile records the exact version, download location and integrity hash of every package in the tree. Because ^5.4.0 could mean many versions, the lockfile is what makes two installs of the same project identical. Always commit it to git for applications. Use npm ci in CI and production builds: it deletes node_modules, installs exactly what the lockfile says, and fails if the lockfile and package.json disagree.

Never commit node_modules itself; it is large and recreated by npm ci. How Node searches it is the topic of the next example. When code asks for a bare name such as chalk, Node looks in ./node_modules/chalk, then ../node_modules/chalk, and so on up to the root.

Node.js How bare names are found in node_modules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Here we fake an installed package by writing the folder ourselves, which is exactly what npm install does after downloading. require.resolve.paths lists the folders searched, nearest first.

Every dependency you install is code you run, and its dependencies too. Supply-chain attacks (typo-squatted names, hijacked maintainer accounts, malicious install scripts) are real. Keep the tree small, review new dependencies, commit the lockfile, run npm audit, and consider npm ci --ignore-scripts in untrusted contexts.

Scripts

The scripts field names commands. npm run build runs the script called build; npm start and npm test are shortcuts. npm adds node_modules/.bin to the PATH for the duration of the command, so a script can call eslint or tsc without a global install. Hooks pre<name> and post<name> run automatically before and after a script of that name.

Node can also do this itself without npm: node --run test runs a script from the nearest package.json, starting faster because it skips npm's startup (see Running Node). A script runner is simple enough to rebuild:

Node.js A mini npm run

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The runner looks for prebuild, then build, then postbuild, and skips names that do not exist, which is what npm does. It starts each command by name with execFile instead of a shell; see Child Processes. Real npm runs each script through the system shell, which is why scripts can use &&, pipes and environment variables. Scripts that must work on both Windows and Linux should avoid shell-specific syntax such as rm -rf; use a Node script instead.

Dev workflow: watch mode, nodemon, cross-env and script chaining

The scripts you write in your first week are tiny. A few habits and tools make the daily loop (edit, restart, run, check) much smoother. Everything here is read-only except for the two runnable demos that show what the tools do inside.

Restarting automatically

Stopping and restarting the server after every edit gets old quickly. Two options exist:

JSON
{
  "scripts": {
    "dev": "node --watch --env-file=.env src/server.js",
    "dev:legacy": "nodemon --watch src --ext js,json src/server.js"
  }
}

node --watch is built in (stable since Node 22): it restarts the process when the entry file or any module it imports changes, and --watch-path=./src adds folders to watch. nodemon is the long-standing package for the same job with more knobs: file extensions to watch (ext), folders to ignore, a restart delay, and a different executable (exec: "ts-node"), configured in nodemon.json or package.json. For a new project the built-in flag is usually enough. Both are development tools only; in production a process manager or container restarts the app (see Deploying Node.js Applications).

Inside, a watcher is small: watch a folder, wait until the burst of change events is over (editors often write a file several times in a row), kill the child process and start it again. This runs a real child process and rewrites its source file:

Node.js What nodemon does: watch, debounce, restart

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Environment variables across operating systems

A script such as "start": "NODE_ENV=production node app.js" works in Linux and macOS shells, but fails in Windows cmd.exe, which has no VAR=value command syntax. The classic fix is the cross-env package: "start": "cross-env NODE_ENV=production node app.js". All it does is set the variables in the environment of the child process it starts. Today there are often simpler routes: node --env-file=.env loads a file of variables (see Running Node), node --run executes scripts without a shell dialect for the simple cases, and a small config.js can give NODE_ENV a sensible default so you rarely need to set it in the script at all.

Node.js What cross-env does, and how && ; chains behave

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Chaining and passing arguments

  • npm run lint && npm test && npm run build stops at the first failing step (a non-zero exit code), which is what a pre-commit hook or CI job wants. ; runs every step regardless, and || runs the next only after a failure. These operators are shell syntax, so on Windows they work in cmd and PowerShell 7 but not in old Windows PowerShell for &&.
  • To run scripts in parallel, such as a server and a TypeScript compiler in watch mode, use a package such as npm-run-all (run-p dev:*) or concurrently, or & on Unix shells only. Keep the output readable by naming each process.
  • Pass arguments to the underlying command after --: npm run test -- --watch runs node --test --watch. Without the --, npm would swallow the flag.
  • Compose with other scripts instead of copying commands: "check": "npm run lint && npm test". The pre and post hooks from the previous section run around each one.
  • Read context from the environment. npm sets npm_package_version, npm_lifecycle_event and friends, but prefer reading package.json directly in code (see "Finding the package.json from code" below) since node --run does not set all of them.
  • Colours in logs. Tools decide on colour by checking whether the output is a terminal. FORCE_COLOR=1 and NO_COLOR=1 override that (useful in CI), and util.styleText('green', 'ok') from node:util adds colour to your own messages without a package.

A good rule for the scripts block: a new teammate should be able to run npm install && npm run dev and see the app working, and npm test should pass or fail with the same result on every machine and operating system.

npx and package executables

npx runs a package's command, downloading it temporarily if needed (read-only here):

Terminal
npx create-vite@latest my-app     # run a project generator once
npx eslint .                      # run a locally installed tool
npm exec -- prettier --check .    # same as npx, the long form

Installed packages expose commands through their bin field. See Creating and Publishing Packages for how to build one yourself, and Building Command-Line Tools.

Workspaces

A monorepo keeps several packages in one repository. With the workspaces field, one npm install at the root installs every package and links local ones together, so they can depend on each other without publishing:

JSON
{
  "name": "acme-monorepo",
  "private": true,
  "workspaces": ["packages/*", "apps/*"]
}
Terminal
npm run test --workspaces           # run a script in every workspace
npm install -w packages/api lodash  # add a dependency to one workspace

Finding the package.json from code

Sometimes your code wants its own package.json, for example to print the version. Recent Node versions offer findPackageJSON in node:module; reading the file yourself also works.

Node.js Locating the nearest package.json

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

For the package that owns the current file you can also use an import attribute: import pkg from './package.json' with { type: 'json' }. Either way, avoid reading process.env.npm_package_version, which exists only when started through npm run.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the range ^1.4.2 allow npm to install?

    The caret allows changes that do not modify the left-most non-zero part: same major version, at least 1.4.2. The tilde (~1.4.2) would stop below 1.5.0.
  2. 2. Why should an application commit package-lock.json and use npm ci in CI?

    Ranges like ^5.4.0 can resolve to different versions over time. The lockfile pins the exact tree, and npm ci installs precisely that.
  3. 3. Which package.json field makes .js files load as ES modules?

    The type field decides how .js files in the package load: "module" for ES modules, "commonjs" (the default) for CommonJS.
  4. 4. What is the difference between dependencies and devDependencies?

    Production installs (npm ci --omit=dev) skip devDependencies, so anything your code imports at runtime must be in dependencies.
  5. 5. What does the imports field with keys like "#format" provide?

    Subpath imports start with # and are visible only to files in the same package, which avoids long relative paths without a bundler.

Summary

  • package.json describes a project: identity (name, version), module format (type), entry points (exports, main, bin), scripts, dependencies and engines.
  • Nearest package.json wins: Node walks up from each file to find it.
  • exports defines the public API of a package; imports defines private #aliases inside it.
  • Semver is MAJOR.MINOR.PATCH; ^ allows minor and patch updates, ~ allows patch updates, and 0.x is stricter.
  • package-lock.json pins the exact tree; commit it and use npm ci for reproducible installs.
  • dependencies are for runtime, devDependencies for tooling; every dependency is code you run, so keep the tree small and audited.
  • Scripts run with npm run (or node --run); npx runs package commands; workspaces manage monorepos.
  • Our editor cannot run npm, so install commands are read-only while the underlying ideas are shown with runnable stand-ins.

Next: Creating and Publishing Packages turns your own code into a package other people can install.