π¦ What is npm?
npm stands for Node Package Manager.
It's the default package manager bundled with Node.js β installing Node automatically gives you npm.
Lets you install, manage, update, and share reusable code, called "packages" or "modules."
π§ Think of it as a massive online registry of libraries and tools built by other developers, ready to plug into your app instead of building everything yourself.
βοΈ What npm Actually Does
Installs packages β pulls code from the npm registry into your project.
Tracks versions β records exactly which version of each package your project uses.
Manages dependencies β handles the web of packages-that-depend-on-other-packages automatically.
Runs scripts β lets you define custom commands (like
npm startornpm run build) inpackage.json.
π€ Why Use npm?
Avoid reinventing the wheel β use
expressinstead of writing a full server from scratch.Share your own libraries β publish your own packages for others (or your future self) to reuse.
Easily manage project dependencies β one file (
package.json) tracks everything your project needs.Stay up to date β update packages and pull in bug fixes or new features with a single command.
π npm Has Three Parts
The registry β the online database where packages live (like
github)The CLI β the
npmcommand you run in your terminal.The website β npmjs.com, where you can browse and search packages.
π¦ Types of Packages in Node.js
Not every require() in your code pulls from the internet. Node draws from three different sources, depending on what you're importing.
Ship with Node.js itself β no installation needed.
Provide low-level functionality like file access, networking, and cryptography.
Imported by name only, with no path or npm install.
const fs = require('fs');
const http = require('http');
const path = require('path');Examples:
fs,http,path,os,crypto,events,util.π‘ Node checks these first β if the name matches a core module, it never touches
node_modules/.
Written by other developers and published to the npm registry.
Must be installed first, then imported by name.
npm install lodashconst _ = require('lodash');Live inside
node_modules/and get listed inpackage.json.Examples:
lodash,express,axios,dotenv.
Files you write yourself, as part of your own project.
Imported using a relative path β never a bare name β so Node knows to look on disk, not in
node_modules/.
// utils.js
function greet(name) {
return `Hello, ${name}!`;
}
module.exports = { greet };// index.js
const { greet } = require('./utils');
console.log(greet('Bhaskar'));The
./prefix is what tells Node "this is a local file," not a package to look up.Great for splitting your own code into organized, reusable pieces.
π§ How Node Decides Where to Look
When you call require('something'), Node checks in this order:
Is it a core module? (
fs,path, etc.) β use the built-in one.Does the path start with
./or../? β treat it as your own local file.Otherwise β search
node_modules/for a matching external package.