npm and Packages
npm is the node package manager. It installs together with Node.js, so you already have it. A package is a piece of reusable code that someone else wrote and shared. npm gives you access to more than a million of them, and it handles downloading, updating, and removing them for you.
A package.json file sits at the heart of every npm project. It lists the packages your project uses, their versions, and a few details like the project name. When you run npm install in a folder, npm reads that file and installs everything listed. When you share your code, a new teammate runs npm install once and gets the exact same setup.
Beginners often skip npm init, and that causes confusing errors later. Without a package.json, npm still installs packages, but your project has no record of what it depends on. A friend clones your project, runs the code, and gets module not found. The fix takes one command: npm init. Run it once in every project folder before installing anything.
Installed packages live in a folder called node_modules. You should never edit files there, and never commit the folder to version control, because it can be recreated from package.json at any time. If something breaks, deleting node_modules and running npm install again gives you a clean start.
Start a project
The npm init command creates package.json. Run it with the --yes flag to accept the defaults without answering questions. You can also write the file by hand if you prefer, because package.json is just text. Open it after init and read what it says: the name, the version, and an empty dependencies list, ready to be filled.
npm init --yes
Install a package
The npm install command adds a package to the project. npm saves it to package.json by default, so there is no extra flag to remember. Look at the file after installing and you will see the package listed under dependencies. A folder called node_modules appears too, and that is where the package code actually lives.
npm install express
Remove a package
Removing a package is just as easy. The uninstall command deletes the package from node_modules and from your package.json. The npm ls command lists everything installed, which helps when you forget what you added. Old tutorials mention a --save flag, but npm has saved to package.json by default since version 5, so you do not need it.
npm uninstall express
npm ls
Syntax
# create package.json without answering questions
npm init --yes
# download express and record it as a dependency
npm install express
# list what is installed
npm ls
npm install Without --save Still Saves in npm 7+
Since npm 7, install saves to dependencies by default — no need for --save.
npm install express
Good to know
- npm init creates package.json.
- npm install saves packages to package.json by default.
- node_modules is recreated from package.json.
- Do not edit files inside node_modules.