πŸ“¦ Day 5: Understanding NPM, Creating package.json, and Installing Dependencies in Node.js

Payal PorwalPayal Porwal
6 min read

πŸ‘¨β€πŸ« What You’ll Learn Today:

  • What is NPM?

  • What is package.json and why it’s important

  • How to create a package.json file

  • How to install, uninstall, and use packages (dependencies)

  • Real-life use cases

  • Common FAQs


πŸ“Œ What is NPM?

NPM stands for Node Package Manager.
It is a tool that comes with Node.js and helps us:

  • Install libraries or tools (called "packages")

  • Manage project dependencies

  • Run custom scripts

πŸ” Think of NPM like Play Store but for backend tools, packages, and code utilities.


πŸ” How to Check if NPM is Installed?

Open your terminal and run:

npm -v

You’ll see a version number like:

10.5.0

πŸ“ What is package.json?

package.json is a configuration file that stores:

  • Project name, version, and description

  • Installed packages (dependencies)

  • Custom scripts (like npm start)

  • Project metadata (author, license, etc.)


🧠 Why is it important?

βœ… It allows others (or you) to download your code and just run:

npm install

…to get everything your project needs.


πŸ› οΈ How to Create a package.json File

Open terminal in your project folder and run:

npm init

This will ask you some questions (name, version, entry point, etc.).

If you want to skip all questions and use default values:

npm init -y

It will instantly create a file like this:

{
  "name": "my-project",
  "version": "1.0.0",
  "main": "index.js",
  "license": "ISC"
}

Now your project is officially NPM-ready!


πŸ“₯ Installing Packages (Dependencies)

Let’s say you want to use the chalk package to color your console output.

Step 1: Install the package

npm install chalk

This will:

  • Add a folder called node_modules (where the package is saved)

  • Update package.json and create package-lock.json


Step 2: Use the package in your code

const chalk = require('chalk');

console.log(chalk.green("Success! Your text is green now."));

βœ… Output: Green-colored message in your terminal.


πŸ“¦ Installing Dev Dependencies

Some packages are only needed during development (like nodemon).

Install them with --save-dev:

npm install nodemon --save-dev

πŸ” These go under "devDependencies" in package.json.


❌ Uninstalling a Package

If you no longer need a package:

npm uninstall chalk

It removes the package from node_modules and updates package.json.


πŸš€ Real-Life Project Example

Project Goal: Create a simple terminal tool that prints messages in colors.


Step-by-step:

mkdir color-printer
cd color-printer
npm init -y
npm install chalk

index.js

const chalk = require('chalk');

console.log(chalk.blue("Hello World in Blue"));
console.log(chalk.bold.red("Error! Something went wrong."));

Now run:

node index.js

βœ… Your terminal shows styled, colorful messages. This is useful in CLI tools, loggers, test results, etc.


🧰 NPM Scripts – Running Custom Commands

Inside package.json, you can define custom scripts:

"scripts": {
  "start": "node index.js",
  "dev": "nodemon index.js"
}

Now run:

npm run start
npm run dev

βœ… This saves time and avoids typing long commands.


🧠 Important Files Created:

FilePurpose
package.jsonProject metadata and dependencies
package-lock.jsonExact version lock to avoid bugs
node_modules/Folder where all installed packages are saved

❓ FAQs – Common Doubts


1) What is the difference between npm install chalk and npm install chalk --save-dev?

CommandUse ForSaved In
npm install chalkFor actual project usedependencies
npm install chalk --save-devFor dev-only tools (like nodemon)devDependencies

2) What happens if I delete node_modules?

❌ You’ll lose all packages.
βœ… But you can run npm install again, and it will reinstall everything using package.json.


3) What’s the use of package-lock.json?

It locks exact versions of installed packages so that everyone using your code gets the same result.
βœ… It's auto-generated. Do not delete it.


4) Can we manually install a specific version of a package?

Yes. Use @version like:

npm install chalk@4.1.0

Useful when:

  • You need compatibility with older code

  • The latest version breaks something


5) What is the use of nodemon?

It restarts your Node app automatically when files change. Great for development.

Install as dev dependency:

npm install nodemon --save-dev

Add script in package.json:

"scripts": {
  "dev": "nodemon index.js"
}

Then run:

npm run dev

πŸ“ Practice Tasks

  1. Create a new folder my-app, initialize package.json

  2. Install the chalk package

  3. Create a file app.js and print a colorful message

  4. Uninstall a package and reinstall it

  5. Add a custom script called hello that prints a message using node app.js


βœ… Summary

ConceptDescription
NPMNode's package manager
package.jsonProject info + dependencies list
npm installAdds external libraries
npm uninstallRemoves libraries
NPM ScriptsCustom shortcut commands
Real UseBuilding tools, CLI apps, backend utilities

You're now ready to build real backend projects using NPM and external packages πŸš€

βœ… Project Title: "Colorful Message Generator" (Using NPM + Express + Chalk)


🧠 Concepts Covered:

  • NPM initialization (package.json)

  • Installing dependencies (express, chalk)

  • Running Node.js backend server

  • Sending color-coded responses in browser


πŸš€ Final Output:

A browser-based webpage (localhost) that shows colorful success or error messages styled using chalk.


πŸ›  Step-by-Step Instructions


πŸ“ 1. Create Project Folder

mkdir colorful-server
cd colorful-server

πŸ“¦ 2. Initialize NPM

npm init -y

Creates your package.json file.


πŸ“₯ 3. Install Required Packages

npm install express chalk
  • express β†’ to create web server

  • chalk β†’ to color server logs (console)


πŸ“„ 4. Create a File: index.js

const express = require('express');
const chalk = require('chalk');

const app = express();
const PORT = 3000;

app.get('/', (req, res) => {
  console.log(chalk.green("βœ” Home route visited successfully"));
  res.send('<h2 style="color:green;">Welcome to the Colorful Server!</h2>');
});

app.get('/error', (req, res) => {
  console.log(chalk.red("βœ– Error route triggered"));
  res.send('<h2 style="color:red;">Oops! Something went wrong.</h2>');
});

app.listen(PORT, () => {
  console.log(chalk.blueBright(`πŸš€ Server is running on http://localhost:${PORT}`));
});

β–Ά 5. Run Your Server

node index.js

βœ… Output on console:

πŸš€ Server is running on http://localhost:3000

🌐 6. Open in Browser:

And in terminal:

  • Logs will show with green or red messages (from chalk)

πŸ“š Bonus for Students

You can create more routes like:

app.get('/info', (req, res) => {
  console.log(chalk.cyan("β„Ή Info route hit"));
  res.send('<h2 style="color:blue;">This is an informational message.</h2>');
});

βœ… Summary of What Students Learn

FeatureLearning Outcome
npm init -yCreate package.json
npm installInstall express and chalk
require() usageUse installed dependencies in code
Express serverBackend development intro
Chalk in terminalBeautify logs (real project feel)
Live browser testingSee real-time output via localhost

πŸŽ“ Ideal Use for Class

  • Students understand NPM dependencies practically

  • No need to learn frontend for now β€” just use HTML in res.send()

  • Easily explain the difference between terminal output and browser output


Would you like me to prepare:

10
Subscribe to my newsletter

Read articles from Payal Porwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Payal Porwal
Payal Porwal

Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: πŸš€ In-depth explorations of emerging technologies πŸ’‘ Practical tutorials and how-to guides πŸ”§Insights on software development best practices πŸš€Reviews of the latest tools and frameworks πŸ’‘ Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Let’s connect and grow together! 🌟