What is NPM?
NPM (Node Package Manager) is the default package manager for Node.js. It downloads, installs and manages reusable packages (libraries/modules). It also maintains project dependencies using package.json and package-lock.json.
Popular Packages
- Express
- Mongoose
- Axios
- React
- dotenv
- Nodemon
- Socket.io
npm install
npm install express
npm update
npm uninstall express
package.json & package-lock.json
package.json stores project metadata, scripts and dependencies.
{
"name":"my-node-app",
"version":"1.0.0",
"main":"index.js",
"scripts":{
"start":"node index.js",
"test":"echo \"No tests\""
},
"dependencies":{
"express":"^4.18.2"
}
}
package-lock.json records the exact versions installed to ensure reproducible installations.
Dependency Types & Installation
| Type | Purpose |
|---|---|
| dependencies | Required in production |
| devDependencies | Development tools |
| optionalDependencies | Optional packages |
npm install express
npm install -g nodemon
npm install --save-dev nodemon
npm install express@4.18.2
Semantic Versioning
MAJOR.MINOR.PATCH
- Major - Breaking changes
- Minor - New features
- Patch - Bug fixes
| Range | Meaning |
|---|---|
| ^1.2.3 | Minor + Patch updates |
| ~1.2.3 | Patch updates only |
| 1.2.3 | Exact version |
NPM Scripts
// index.js
console.log("Hello from my first npm script!");
// package.json
"scripts":{
"start":"node index.js",
"dev":"node index.js",
"test":"echo \"Running tests...\""
}
npm start
npm run dev
npm test
Node.js Global Objects
global
global.a="Hello";
console.log(a);
console
console.log("Message");
console.error("Error");
console.warn("Warning");
process
console.log(process.pid);
console.log(process.version);
console.log(process.platform);
Calculator using process.argv
let n1=Number(process.argv[2]);
let op=process.argv[3];
let n2=Number(process.argv[4]);
Buffer
const buffer=Buffer.from("Hello Node.js");
console.log(buffer);
__dirname & __filename
console.log(__dirname);
console.log(__filename);
Timers
setTimeout(()=>console.log("After 2 sec"),2000);
setInterval(()=>console.log("Every 3 sec"),3000);
URL & URLSearchParams
const u=new URL("https://example.com/?name=Lily");
console.log(u.searchParams.get("name"));
TextEncoder & TextDecoder
const enc=new TextEncoder();
const data=enc.encode("Hello");
const dec=new TextDecoder();
console.log(dec.decode(data));
| Object | Purpose |
|---|---|
| global | Application-wide scope |
| console | Logging |
| process | Runtime information |
| Buffer | Binary data |
| __dirname | Current directory |
| __filename | Current file path |
| URL | URL parsing |
| TextEncoder/TextDecoder | Encode/Decode UTF-8 |