Packages and the registry
A package is a folder of reusable code with a package.json file that names it. npm, the package manager installed with Node.js, downloads packages from the npm registry, a huge public online library of them.
Installing a package
In an empty folder, npm init -y writes package.json, the description of your project: its name and version. You add a script named start that runs node index.js. Every npm project has this file.
npm install ms asks the registry about the package ms. You named no version, so npm takes the one tagged latest, 2.1.3, and downloads it as a tarball: one compressed file holding the package folder.
npm unpacks it into node_modules/ms: its code and its own package.json. ms needs no other packages. If it did, npm would install those too, also inside node_modules.
npm adds "ms": "^2.1.3" to dependencies. The caret means any 2.x.y version from 2.1.3 up, but not 3.0.0. A new major version may break your code, so it is never picked automatically.
npm also writes package-lock.json. It records the exact version installed, 2.1.3, where it came from, and an integrity hash of the tarball. Later installs use this file and check that hash.
Using it
npm start looks up start in the scripts of package.json and runs its command, node index.js. Scripts give everyone on a project the same short names for common jobs.
require("ms") names a package, not a path, so Node looks for a node_modules/ms folder. It reads the package's package.json, whose main field points to ./index, loads index.js and returns its function.
ms("2 days") turns the text into milliseconds: 2 × 24 × 60 × 60 × 1000 = 172800000. console.log prints it in the terminal. One line of your code used code you never had to write.
Sharing the project
You share the project without node_modules. A teammate runs npm ci: it deletes any node_modules, downloads exactly what the lock file lists from the registry, checks every hash, and stops if package.json and the lock disagree.
What happens
// step 1/10 · registry package a folder of code + its own package.json npm the package manager installed with Node.js registry registry.npmjs.org, the public library example ms: turns "2 days" into milliseconds recent 2.1.1, 2.1.2, 2.1.3 (latest 2.1.3)
npm init -y also writes description, main, keywords, author, license, type and a placeholder test script; the card shows only the fields this lesson uses, and npm writes each object over several lines. require is Node's CommonJS module system. With "type": "module" in package.json you would write import ms from "ms", the standard ECMAScript import; Node finds the package in node_modules the same way.