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

Running JavaScript in Node.js

Learn how to create JavaScript files, execute programs using Node.js, understand terminal output, work with variables and functions, and troubleshoot common execution errors.

1. Introduction to Running JavaScript

JavaScript can run in different environments. A browser executes JavaScript for webpage interactions, while Node.js executes JavaScript outside the browser.

To run JavaScript using Node.js, we write code in a file with the .js extension and execute that file through the terminal. Node.js reads the file and runs its JavaScript statements.

Important Concept: The command node filename.js runs the specified JavaScript file. Make sure Node.js is installed and available in your terminal before executing the command.

Ways to Execute JavaScript

Method How It Works Suitable For
Node.js REPL Executes expressions interactively. Quick experiments and calculations.
JavaScript File Executes code saved in a .js file. Programs and reusable logic.
npm Script Runs a command configured in package.json. Project workflows and development commands.

2. JavaScript Execution Workflow

The following diagram shows how a JavaScript file is executed using Node.js.

Write JavaScript Code
app.js
↓
Save the File
↓
Open the Terminal in the Project Folder
↓
Execute node app.js
↓
View the Output in the Terminal

If the program contains an error, Node.js may display an error message instead of completing the program successfully.

3. Create Your First JavaScript File

Let us create a simple JavaScript program that prints a welcome message for Samadhan and Pradnya.

Step 1: Create a Project Folder

Create a folder named NodeJsPractice on your computer. Open this folder in your code editor.

Step 2: Create app.js

Inside the folder, create a file named app.js and write the following code.

app.js
console.log("Welcome to Node.js!");

console.log("Hello Samadhan!");
console.log("Hello Pradnya!");

console.log("Welcome to CIIT TRAINING INSTITUTE.");

Step 3: Save the File

Save the file with the exact name app.js. Ensure that the file is not accidentally saved as app.js.txt.

Expected Project Structure

Folder Structure
NodeJsPractice/
└── app.js

4. Execute JavaScript Using Node.js

After creating and saving the file, execute it from the terminal.

Step 1: Open the Terminal

Open the terminal in the NodeJsPractice folder. You can use your code editor's integrated terminal or Command Prompt.

Step 2: Run the Command

Terminal
node app.js

Expected Output

Welcome to Node.js!
Hello Samadhan!
Hello Pradnya!
Welcome to CIIT TRAINING INSTITUTE.

Command Explanation

  • node starts the Node.js runtime.
  • app.js specifies the JavaScript file to execute.
  • console.log() prints each message to the terminal.
Remember: Run the command from the directory containing app.js, or provide the correct relative path to the file.

5. Run JavaScript with Variables

JavaScript files can contain variables, calculations, conditions, loops, and functions. Node.js executes these statements in order, subject to the program's control flow.

Example: Calculate Total Marks

marks.js
const samadhanMarks = 80;
const pradnyaMarks = 90;

const totalMarks = samadhanMarks + pradnyaMarks;

console.log("Samadhan's Marks:", samadhanMarks);
console.log("Pradnya's Marks:", pradnyaMarks);
console.log("Combined Total:", totalMarks);

Execute the File

Terminal
node marks.js

Expected Output

Samadhan's Marks: 80
Pradnya's Marks: 90
Combined Total: 170

Explanation

  • const declares a variable binding that cannot be reassigned.
  • samadhanMarks stores the first marks value.
  • pradnyaMarks stores the second marks value.
  • totalMarks stores the sum of both values.
  • The final statements print the stored values.

6. Execute JavaScript Functions

Functions allow us to organize reusable logic. A function can accept parameters, process values, and return a result.

Example: Calculate Total Fees

fees.js
function calculateTotalFees(firstInstallment, secondInstallment) {
    return firstInstallment + secondInstallment;
}

const samadhanFees = calculateTotalFees(10000, 5000);
const pradnyaFees = calculateTotalFees(12000, 8000);

console.log("Samadhan's Total Fees:", samadhanFees);
console.log("Pradnya's Total Fees:", pradnyaFees);

Execute the Program

Terminal
node fees.js

Expected Output

Samadhan's Total Fees: 15000
Pradnya's Total Fees: 20000

Code Explanation

  • calculateTotalFees() defines a reusable function.
  • The parameters receive the installment values.
  • return sends the calculated total back to the caller.
  • The function is called separately for Samadhan and Pradnya.

7. Understand JavaScript Execution Order

JavaScript normally executes synchronous statements in order. Understanding this order helps us predict the program's output.

Example

order.js
console.log("Step 1");

const number = 10;

console.log("Step 2");

const result = number * 2;

console.log("Result:", result);
console.log("Step 3");

Expected Output

Step 1
Step 2
Result: 20
Step 3

Execution Flow Diagram

Print Step 1
↓
Assign number = 10
↓
Print Step 2
↓
Calculate result = 20
↓
Print Result and Step 3

8. Run Different JavaScript Files

A project can contain multiple JavaScript files. You can execute a specific file by passing its name to the Node.js command.

Example Project Structure

Folder Structure
NodeJsPractice/
├── app.js
├── marks.js
└── fees.js

Run the First File

Terminal
node app.js

Run the Second File

Terminal
node marks.js

Run the Third File

Terminal
node fees.js
Important: Each command executes the file you specify. Creating multiple files does not automatically execute all of them.

9. Common JavaScript Execution Errors

Error Possible Reason Solution
Node.js is not recognized Node.js is unavailable in the current terminal environment. Check the installation and PATH configuration.
Cannot find module or file The filename or file path is incorrect. Verify the file name and current directory.
SyntaxError The JavaScript contains invalid syntax. Check brackets, quotation marks, and statement structure.
ReferenceError The code refers to a variable that is not defined in the current scope. Check the variable name and declaration.
Unexpected output The saved code or input values differ from what was expected. Save the file and check the program statements.
Debugging Tip: Read the complete error message and identify the filename and line number when provided. Correct the underlying issue and execute the program again.

10. CIIT Training Institute - Practice Task

Task: Create a Student Result Program

Create a file named studentResult.js and complete the following tasks:

  1. Store the names Samadhan and Pradnya in variables.
  2. Store marks for three subjects for each student.
  3. Calculate each student's total marks.
  4. Calculate each student's average marks.
  5. Display the student names, totals, and averages.
  6. Run the program using node studentResult.js.
Sample Solution
studentResult.js
const samadhan = {
    name: "Samadhan",
    marks: [80, 75, 85]
};

const pradnya = {
    name: "Pradnya",
    marks: [90, 88, 92]
};

function calculateTotal(marks) {
    return marks.reduce((total, mark) => total + mark, 0);
}

function displayResult(student) {
    const total = calculateTotal(student.marks);
    const average = total / student.marks.length;

    console.log("Student:", student.name);
    console.log("Total:", total);
    console.log("Average:", average);
    console.log("--------------------");
}

displayResult(samadhan);
displayResult(pradnya);
Expected Output
Student: Samadhan
Total: 240
Average: 80
--------------------
Student: Pradnya
Total: 270
Average: 90
--------------------

This exercise combines variables, arrays, objects, functions, calculations, and console output in a single Node.js program.

Summary

Running JavaScript in Node.js involves creating a JavaScript file, saving the code, opening a terminal in the correct directory, and executing the file with the node command. We learned how to print messages, use variables, perform calculations, execute functions, understand statement order, run multiple files, and troubleshoot common errors. Practical exercises at CIIT TRAINING INSTITUTE help students develop confidence in writing and executing JavaScript programs.