Node.js Lesson 4: npm — Package Manager

🟢 Node.js CourseLesson 4 of 15 · 27% complete

npm (Node Package Manager) gives you access to 2+ million open-source packages. It’s how you add libraries, manage dependencies, and share your own code.

Essential npm Commands

# Start a new project
npm init -y         # creates package.json with defaults

# Install a package
npm install lodash  # installs lodash, saves to package.json
npm install -D nodemon  # devDependency (only for development)

# Install from package.json (after cloning a repo)
npm install

# Remove a package
npm uninstall lodash

# Run scripts
npm start
npm run dev
npm test

package.json

{
  "name": "my-project",
  "version": "1.0.0",
  "scripts": {
    "start": "node app.js",
    "dev": "nodemon app.js",  // auto-restart on file save
    "test": "jest"
  },
  "dependencies": {
    "express": "^4.18.2",
    "lodash": "^4.17.21"
  },
  "devDependencies": {
    "nodemon": "^3.0.1"
  }
}

Using Packages

const _ = require("lodash");

// lodash utilities
const arr = [3, 1, 4, 1, 5, 9, 2, 6];
console.log(_.uniq(arr));           // [3,1,4,5,9,2,6]
console.log(_.max(arr));            // 9
console.log(_.chunk(arr, 3));       // [[3,1,4],[1,5,9],[2,6]]
console.log(_.capitalize("hello")); // "Hello"
console.log(_.range(1, 6));         // [1,2,3,4,5]

🏋️ Practice Task

Create a new Node project (npm init -y). Install chalk (for colored terminal output) and dayjs (for date formatting). Write a script that logs: today’s date formatted as “MMMM D, YYYY”, a green success message, and a red error message.

💡 Hint: npm install chalk dayjs. const chalk = require(“chalk”); const dayjs = require(“dayjs”). Note: chalk v5 is ESM only — install chalk@4 for CommonJS.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *