npm, package.json and Semantic Versions
Manage a Node.js project with npm: create package.json, add a dependency, run scripts, read the lock file, and understand semantic version ranges with the real semver package checked against an independent implementation.
In this lesson you will
- Create and read package.json
- Install a dependency and run a script
- Explain what the lock file is for
- Read caret and tilde ranges
About 28 minutes
Not writing everything yourself
Mara’s tool needs a date formatter and a CSV parser, and writing them again would be a waste, since thousands of small libraries exist. npm, the Node package manager, installs them. A project is described by a file called package.json: its name and version, the scripts that can be run with npm run, and its dependencies, the packages it needs, each with a version range. npm install downloads the packages into the node_modules folder, and writes package-lock.json, which records the exact version of every package that was installed, including the dependencies of dependencies, so that everyone who installs the project gets the same tree.
Versions follow semantic versioning: three numbers, major.minor.patch. A patch release fixes bugs, a minor release adds features without breaking anything, and a major release may break things. Ranges in package.json use this. The caret ^1.2.3 allows any version from 1.2.3 up to, but not including, 2.0.0: new features and fixes, no breaking changes. The tilde ~1.2.3 allows only patch updates, up to but not including 1.3.0. Versions below 1.0.0 are treated more strictly, since anything may change: ^0.2.3 allows only 0.2.x. Every package you install is code from somebody else that runs with your permissions, so choose carefully, keep dependencies few, and run npm audit regularly.
| Range | Allows | Does not allow |
|---|---|---|
| ^1.2.3 | 1.2.3 up to 1.x.x | 2.0.0 |
| ~1.2.3 | 1.2.3 up to 1.2.x | 1.3.0 |
| 1.2.3 | Exactly that version | Anything else |
| ^0.2.3 | 0.2.3 up to 0.2.x | 0.3.0 |
| * | Any version | Nothing |
set -e
cd "$(mktemp -d)"
mkdir -p pkgs/greeter
cat > pkgs/greeter/package.json <<'EOF'
{ "name": "greeter", "version": "1.4.2", "main": "index.js" }
EOF
echo "module.exports = name => 'Hello, ' + name + '!';" > pkgs/greeter/index.js
npm init -y --silent >/dev/null
echo "console.log(require('greeter')('Mara'));" > hello.js
node -e "
const fs = require('fs'); const p = JSON.parse(fs.readFileSync('package.json'));
p.name = 'print-shop'; p.scripts = { hello: 'node hello.js', test: 'echo tests would run here' };
fs.writeFileSync('package.json', JSON.stringify(p, null, 2));"
npm install ./pkgs/greeter --no-audit --no-fund --silent
echo "--- package.json dependencies"
node -p "JSON.stringify(require('./package.json').dependencies)"
echo "--- npm run hello"
npm run hello --silent
echo "--- lock file"
node -p "const l = require('./package-lock.json'); JSON.stringify({ lockfileVersion: l.lockfileVersion, packages: Object.keys(l.packages) })"
echo "--- installed folder"
ls node_modules
echo "--- npm ls"
npm ls --depth=0 | sed 's/@.*//; s#.*/##' | head -3
--- package.json dependencies
{"greeter":"file:pkgs/greeter"}
--- npm run hello
Hello, Mara!
--- lock file
{"lockfileVersion":3,"packages":["","node_modules/greeter","pkgs/greeter"]}
--- installed folder
greeter
--- npm ls
print-shop
└── greeter
const semver = require('semver');
const cases = [['^1.2.3', '1.9.0'], ['^1.2.3', '2.0.0'], ['^1.2.3', '1.2.2'], ['~1.2.3', '1.2.9'], ['~1.2.3', '1.3.0'], ['^0.2.3', '0.2.9'], ['^0.2.3', '0.3.0'], ['1.2.3', '1.2.4'], ['>=2.0.0 <3.0.0', '2.5.1'], ['*', '10.0.0']];
const rows = cases.map(([r, v]) => ({ range: r, version: v, ok: semver.satisfies(v, r) }));
rows.forEach(x => console.log(x.range.padEnd(16), x.version.padEnd(8), x.ok ? 'allowed' : 'not allowed'));
const list = ['1.10.0', '1.2.0', '1.9.1', '1.2.10', '2.0.0', '1.2.2'];
console.log('sorted by semver:', semver.sort([...list]).join(' < '), '| sorted as text:', [...list].sort().join(' < '));
console.log('DATA ' + JSON.stringify({ rows, sorted: semver.sort([...list]), text: [...list].sort() }));
^1.2.3 1.9.0 allowed
^1.2.3 2.0.0 not allowed
^1.2.3 1.2.2 not allowed
~1.2.3 1.2.9 allowed
~1.2.3 1.3.0 not allowed
^0.2.3 0.2.9 allowed
^0.2.3 0.3.0 not allowed
1.2.3 1.2.4 not allowed
>=2.0.0 <3.0.0 2.5.1 allowed
* 10.0.0 allowed
sorted by semver: 1.2.0 < 1.2.2 < 1.2.10 < 1.9.1 < 1.10.0 < 2.0.0 | sorted as text: 1.10.0 < 1.2.0 < 1.2.10 < 1.2.2 < 1.9.1 < 2.0.0
The shell script created a real npm project in a temporary folder, with a tiny local package called greeter, version 1.4.2, installed with npm install from its folder. The result is what the output block shows: package.json now lists the dependency as file:pkgs/greeter, the script named hello, run with npm run, printed “Hello, Mara!” by loading the package from node_modules, and the lock file lists the packages that npm installed, the project itself, the link in node_modules and the folder it points to. For a package from the registry, the dependency would carry a version range such as ^1.4.2 and the lock file would pin the exact version and a checksum of its contents.
The second program tests the version rules with the real semver package, the library npm itself uses. ^1.2.3 allows 1.9.0; ~1.2.3 allows 1.2.9; ^0.2.3 allows 0.2.9; >=2.0.0 <3.0.0 allows 2.5.1; * allows 10.0.0. And ^1.2.3 refuses 2.0.0; ^1.2.3 refuses 1.2.2; ~1.2.3 refuses 1.3.0; ^0.2.3 refuses 0.3.0; 1.2.3 refuses 1.2.4. The last line of its output shows a classic mistake: sorted as text, version 1.10.0 comes before 1.2.0, because "1" is smaller than "2" as a character, while the semver sort puts it in the right place. Always compare versions with a semver library and never as strings.
Independent check: a second implementation of the range rules, written in Python from the definitions in the text, with caret and tilde limits calculated by hand, agrees with the semver package on all ten cases, and its sort by numeric version triple gives the same order as the library’s sort. The lock file is checked by its contents: the packages list contains exactly the project, the link and the source folder.
Check by hand: ^1.2.3 allows everything below 2.0.0 and from 1.2.3, so 1.9.0 is allowed, 1.2.2 is too old and 2.0.0 is too new. ~1.2.3 allows up to but not including 1.3.0. For ^0.2.3 the leading zero makes the minor number the breaking one, so the limit is 0.3.0.
Commit package-lock.json so that installs are repeatable. Every dependency is code that runs with your permissions: check how widely used and maintained a package is, and run npm audit.
npm ci installs exactly what the lock file says and fails if package.json and the lock file disagree, which makes builds repeatable. npm install is for changing dependencies on your own machine.
Every program in this lesson was run while the course was written, with Node.js 22 and only its built-in modules (plus the packages named in the lesson), and cross-checked with the shell, curl, Python or the specification. Node.js releases change, so check nodejs.org for the current long-term support version and its documentation. The lock file format and some npm output change between npm versions. Check the npm documentation for your version.
Practice
Create a project with npm init, install a small package from the registry, and look at the lock file. Write the range that allows 3.1.x only. Add a script that runs your tests and a script named start.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does package-lock.json do?
- Records exact versions of every installed package
- Locks the folder
- Hides packages
- Compresses node_modules
Repeatable installs.
What does ^1.2.3 allow?
- Only 1.2.3
- 1.2.3 to 1.2.9
- Any version
- 1.2.3 up to but not including 2.0.0
Compatible minor and patch updates.
What does ~1.2.3 allow?
- Any 1.x
- Only 1.2.3
- 2.0.0
- Patch updates up to but not including 1.3.0
Tilde is stricter than caret.
Why is sorting versions as text a mistake?
- Text is slower
- Versions are numbers only
- 1.10.0 sorts before 1.2.0 as text
- Sorting is forbidden
Use a semver library.
What does npm ci do?
- Updates all packages
- Deletes packages
- Installs exactly from the lock file
- Publishes the project
Used in automated builds.
Summary
- package.json describes the project, and the lock file pins exact versions.
- Semantic versions are major.minor.patch.
- Caret allows compatible updates, tilde only patches.
- Review dependencies and use npm ci in builds.
Questions
What is node_modules and should I commit it?
It is the folder of installed packages, and it can be rebuilt from package.json and the lock file. Do not commit it, add it to .gitignore.
What is the difference between dependencies and devDependencies?
dependencies are needed to run the program, and devDependencies only for development, such as test tools and linters.
How do I publish my own package?
Create an account on the npm registry, set a unique name and version in package.json and run npm publish. Check the npm documentation for current steps and for security options such as two-factor authentication.
