Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security
\

package.json in Node.js

The package.json file is an important configuration file in Node.js projects. It stores project information, dependencies, development dependencies, scripts, and other settings used to manage an application.

Whenever we create a Node.js project using NPM, we can create a package.json file to describe the project and manage the packages required by the application.

Learning objective: Understand the purpose and structure of package.json, learn its important properties, create a package.json file, and use it to manage project scripts and dependencies.

1. What Is package.json?

package.json is a JSON-formatted file that contains metadata and configuration for a Node.js project.

It can store information such as:

  • Project name and version.
  • Project description.
  • Main application entry point.
  • Installed dependencies.
  • Development dependencies.
  • Scripts used to run project commands.
Node.js Project

Application source code

↓
package.json

Project metadata, scripts, and dependencies

↓
NPM

Uses project configuration to manage packages and scripts

2. Create a package.json File

First, create a folder for your Node.js project and open a terminal inside that folder.

Step 1: Create the project folder

Terminal
mkdir StudentApp
cd StudentApp

Step 2: Initialize the project

Terminal
npm init -y

The npm init command can guide you through project setup. Adding -y accepts the default answers and creates package.json without asking each question.

Example package.json

JSON
{
  "name": "studentapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

The generated values may differ depending on your NPM version and the folder name.

3. Important Properties of package.json

Property Purpose Example
name Specifies the project or package name. "studentapp"
version Specifies the project version. "1.0.0"
description Describes the project. "Student management app"
main Declares the package entry point for consumers when applicable. "app.js"
scripts Defines commands that can be run using NPM. "start": "node app.js"
dependencies Lists packages required by the application. "express": "..."
devDependencies Lists packages used for development tasks. "nodemon": "..."
license Specifies the package license. "ISC"
Remember: The main property is not the command that starts every Node.js application. For a project you run directly, the start command is commonly defined inside scripts.

4. Understanding the name and version

The name property identifies the project or package. The version property identifies its current release.

JSON
{
  "name": "student-management",
  "version": "1.0.0"
}

In this example:

  • student-management is the project name.
  • 1.0.0 is the project's version.

A package name should follow NPM's naming rules. In a typical project, the name is lowercase and avoids spaces.

5. Understanding the scripts Property

The scripts property lets developers create shortcuts for frequently used commands.

JSON
{
  "name": "studentapp",
  "version": "1.0.0",
  "scripts": {
    "start": "node app.js",
    "dev": "node app.js"
  }
}

Here, the start script runs node app.js. The dev script runs the same command.

Create app.js

JavaScript
console.log("Student Management Application Started!");

Run the start script

Terminal
npm start

Expected output:

Output
Student Management Application Started!

The start script has a special shorthand: npm start. Other custom scripts can be run with commands such as npm run dev.

6. Dependencies in package.json

Dependencies are packages that an application needs to perform its functionality. For example, a web application may use Express to create routes and handle HTTP requests.

Install Express using:

Terminal
npm install express

NPM adds Express to the project's dependencies property in package.json. The exact version recorded depends on the package version resolved during installation.

JSON
{
  "dependencies": {
    "express": "^4.21.0"
  }
}

The version above is only an illustrative example. Your installed version may be different.

7. Dependencies vs devDependencies

NPM separates packages needed by the application from packages used primarily during development.

dependencies devDependencies
Packages needed by the application at runtime. Packages used for development and testing tasks.
Example: Express for an API. Example: Nodemon for restarting during development.
Install with npm install package-name. Install with npm install package-name --save-dev.

For example, install Nodemon as a development dependency:

Terminal
npm install nodemon --save-dev

NPM records Nodemon under devDependencies.

8. package.json vs package-lock.json

These two files have different responsibilities in a Node.js project.

package.json package-lock.json
Contains project metadata and dependency declarations. Records the resolved dependency tree and exact versions.
Can contain version ranges. Helps reproduce the same dependency resolution.
Can be edited to change project configuration. Usually maintained by NPM when dependencies change.
Best practice: For an application, commit both package.json and package-lock.json to version control so other developers can install the project's intended dependency tree.

9. Complete Project Structure

After creating the project and installing packages, your folder may look like this:

StudentApp/
|
|-- node_modules/
|
|-- app.js
|
|-- package.json
|
|-- package-lock.json

The node_modules directory contains installed packages. The two JSON files describe the project and its dependency information, while app.js contains the application's JavaScript code.

10. Common package.json Errors

Problem Reason Solution
Invalid JSON Missing commas, quotes, or braces. Correct the JSON syntax.
Missing script The requested script is not defined. Add the script under scripts.
Module not found The required package may not be installed. Install the package in the project.
Incorrect package name The name may violate package naming rules. Use a valid project name.

11. Practice Tasks

  1. Create a project named EmployeeApp.
  2. Generate package.json using npm init -y.
  3. Change the project description.
  4. Create app.js and print a welcome message.
  5. Add a start script to package.json.
  6. Install Express as a dependency.
  7. Install Nodemon as a development dependency.

Summary

The package.json file stores important information about a Node.js project, including its name, version, scripts, and dependencies. The npm init -y command creates a default package.json file, while NPM commands can install and remove packages. The dependencies and devDependencies properties separate application packages from development tools. The package-lock.json file records the resolved dependency tree. Understanding package.json helps developers organize, configure, and manage Node.js projects effectively at CIIT TRAINING INSTITUTE.