Node Package Manager (NPM) & Global Objects

Interactive Learning Notes - Unit 3

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

TypePurpose
dependenciesRequired in production
devDependenciesDevelopment tools
optionalDependenciesOptional packages
npm install express
npm install -g nodemon
npm install --save-dev nodemon
npm install express@4.18.2

Semantic Versioning

MAJOR.MINOR.PATCH

RangeMeaning
^1.2.3Minor + Patch updates
~1.2.3Patch updates only
1.2.3Exact 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));
ObjectPurpose
globalApplication-wide scope
consoleLogging
processRuntime information
BufferBinary data
__dirnameCurrent directory
__filenameCurrent file path
URLURL parsing
TextEncoder/TextDecoderEncode/Decode UTF-8