The node_modules Directory
What you'll learn: How node_modules is structured, what lives inside it, and why you should never commit it to version control.
What Is node_modules?
When you run npm install, NPM creates a node_modules directory in your project root. This folder holds all the actual code for every package you've installed—both the ones you explicitly requested and all their dependencies (and their dependencies' dependencies, and so on).
Think of node_modules as a self-contained library warehouse. If you install Express, node_modules doesn't just contain Express's code—it also contains the 30+ packages Express depends on to function.
The Structure Inside
Each installed package gets its own subdirectory inside node_modules. For example:
node_modules/
├── express/
├── body-parser/
├── cookie-parser/
└── ... (dozens or hundreds more)
Each package folder contains the package's source code, its own package.json, and possibly its own nested node_modules for its dependencies (though modern NPM flattens this when possible).
Why Gitignore node_modules?
This directory is huge—often hundreds of megabytes or more. Committing it to Git would:
- Bloat your repository enormously
- Slow down clones and pulls
- Create merge conflicts constantly
- Waste storage on code that's publicly available
Instead, you commit package.json and package-lock.json. Anyone cloning your repo can recreate the exact same node_modules by running npm install.
Always add this line to your .gitignore:
node_modules/
Key Takeaway: The node_modules directory stores all installed packages and their dependencies locally; it's massive, auto-generated, and should always be excluded from version control since package.json and package-lock.json can recreate it exactly.