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

NPM Scripts in Node.js

NPM scripts allow developers to define and execute commands from the scripts section of package.json. They help simplify common development tasks such as starting an application, running tests, checking code, and building a project.

Instead of typing long commands repeatedly, developers can create short, meaningful script names and execute them through NPM.

Learning objective: Understand NPM scripts, configure scripts in package.json, execute custom commands, use pre and post scripts, and create practical scripts for a Node.js application.

1. What Are NPM Scripts?

NPM scripts are commands defined inside the "scripts" property of the package.json file. They provide a convenient way to run commands associated with a project.

For example, we can define a script named start that executes node app.js. Instead of typing the complete command every time, we can run npm start.

Example: package.json

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

Here, start is the script name and node app.js is the command that NPM executes.

package.json

Contains the scripts property

↓
NPM Command

npm start

↓
Node.js Executes app.js

The application starts

2. Why Do We Use NPM Scripts?

NPM scripts are useful for the following reasons:

  • Run an application using a short command.
  • Start a development server.
  • Run automated tests.
  • Check and format source code.
  • Build an application before deployment.
  • Standardize commands across a development team.
Simple example: If the command is node app.js, a script named start lets you execute the same command using npm start.

3. Create a Node.js Project

Let's create a simple project to understand NPM scripts.

Step 1: Create a folder

Terminal
mkdir NpmScriptsDemo
cd NpmScriptsDemo

Step 2: Initialize NPM

Terminal
npm init -y

This creates a default package.json file in the project directory.

Step 3: Create app.js

JavaScript
console.log("Welcome to NPM Scripts!");

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

Project structure

NpmScriptsDemo/
|
|-- app.js
|
|-- package.json

4. Create Your First NPM Script

Open package.json and add a start script inside the existing scripts object.

package.json
{
  "name": "npmscriptsdemo",
  "version": "1.0.0",
  "scripts": {
    "start": "node app.js"
  }
}

If your package.json contains additional properties, keep them. Add the start entry to its existing scripts object.

Run the script

Terminal
npm start

Expected output:

Output
Welcome to NPM Scripts!
Student Management Application Started.

NPM executes the command defined by the start script. In this example, it runs node app.js.

5. Understanding Common NPM Script Commands

Script Command Purpose
npm start Runs the start script.
npm test Runs the test script.
npm run dev Runs a custom script named dev.
npm run build Runs a custom script named build.
npm run lint Runs a custom script named lint.
Remember: Custom scripts are normally executed with npm run script-name. The start and test scripts have convenient shorthand commands. Each script must be defined before it can run.

6. Create Multiple NPM Scripts

A project can define several scripts for different development tasks.

Example package.json

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

These scripts execute different JavaScript files. Create each file before running its corresponding script.

Example: test.js

JavaScript
console.log("Test script executed successfully.");

Run the test script

Terminal
npm test

Expected output:

Output
Test script executed successfully.

This example only prints a message; it does not run a real automated test framework. A real test script normally executes a testing tool or test program.

7. Use Nodemon with NPM Scripts

Nodemon is a development tool that restarts a Node.js application when watched files change. We can create a dev script to run Nodemon conveniently.

Step 1: Install Nodemon

Terminal
npm install nodemon --save-dev

Step 2: Add the dev script

package.json
"scripts": {
  "start": "node app.js",
  "dev": "nodemon app.js"
}

Add these entries to your existing scripts object. Do not create a duplicate scripts property.

Step 3: Run development mode

Terminal
npm run dev

Expected application message:

Output
Welcome to NPM Scripts!
Student Management Application Started.

Nodemon may display additional startup messages in the terminal. When you edit a watched file, it restarts the application. Press Ctrl + C to stop the process.

8. Pass Arguments to NPM Scripts

NPM scripts can accept arguments. When passing additional arguments to a script, use -- to separate the NPM options from the arguments intended for the script.

Example package.json

JSON
{
  "scripts": {
    "greet": "node greet.js"
  }
}

Create greet.js

JavaScript
const name = process.argv[2] || "Student";

console.log(`Hello, ${name}!`);

Run the script with an argument

Terminal
npm run greet -- Samadhan

Expected output:

Output
Hello, Samadhan!

Here, process.argv[2] contains the first application argument, which is Samadhan.

9. Pre and Post Scripts

NPM supports lifecycle scripts that can run before or after certain scripts. For a custom script named build, you can define prebuild and postbuild.

Example package.json

JSON
{
  "scripts": {
    "prebuild": "node prebuild.js",
    "build": "node build.js",
    "postbuild": "node postbuild.js"
  }
}

Create each of the three JavaScript files and add a console.log() statement to each one.

Example: prebuild.js

JavaScript
console.log("Preparing the project...");

Example: build.js

JavaScript
console.log("Building the project...");

Example: postbuild.js

JavaScript
console.log("Build process finished.");

Run the build script

Terminal
npm run build

Expected output:

Output
Preparing the project...
Building the project...
Build process finished.

For custom scripts, NPM runs the matching pre-script before the main script and the matching post-script after it, provided the earlier command succeeds. These examples demonstrate the execution order; they do not perform a real build.

10. Useful NPM Script Commands

Command Purpose
npm start Runs the start script.
npm test Runs the test script.
npm run dev Runs the custom dev script.
npm run build Runs the build script.
npm run Lists the available scripts in the project.
npm run greet -- Samadhan Passes an argument to the greet script.

11. Common NPM Script Errors

Error Reason Solution
Missing script The requested script is not defined. Add the script to package.json.
Cannot find module The JavaScript file or package is missing. Check the file path and install required packages.
Invalid package.json JSON syntax is incorrect. Check commas, quotes, braces, and brackets.
Command not found The required executable may not be installed or available. Install the tool in the project and check the script.
Port already in use Another process is using the required port. Stop the other process or choose another port.

12. Practice Tasks

  1. Create a project named EmployeeApp.
  2. Create a start script to run app.js.
  3. Create a dev script using Nodemon.
  4. Create a test script that prints a message.
  5. Create a greet script that accepts a name.
  6. Create prebuild, build, and postbuild scripts.
  7. Run all scripts from the terminal.
  8. Use npm run to display available scripts.

Summary

NPM scripts are commands defined in the scripts property of package.json. They help developers start applications, run tests, execute development tools, and automate common tasks. The npm start and npm test commands provide convenient shortcuts, while custom scripts are executed with npm run. Arguments can be passed to scripts, and prebuild and postbuild scripts can run before and after a custom build script. Understanding NPM scripts helps developers manage and automate Node.js projects efficiently at CIIT TRAINING INSTITUTE.