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

Node.js Process Object

Learn how to use the Node.js process object to inspect runtime information, identify the Node.js version, read command-line arguments, access environment variables, monitor process events, and control how an application exits.

1. What Is the Node.js Process Object?

The process object is a global object provided by Node.js. It contains information about the currently running Node.js process and provides methods for interacting with it.

A process is an instance of a running program managed by the operating system. When we execute a JavaScript file using Node.js, the operating system runs a Node.js process to execute that application.

The process object helps us access details such as the runtime version, operating system platform, current working directory, command-line arguments, environment variables, and exit events.

Important Concept: We can use process directly in a Node.js JavaScript file. We do not need to import it manually.

Common Process Properties and Methods

Property / Method Purpose Example
process.version Returns the Node.js version. process.version
process.platform Identifies the operating system platform. process.platform
process.arch Identifies the CPU architecture used by the Node.js binary. process.arch
process.cwd() Returns the current working directory. process.cwd()
process.argv Contains command-line arguments. process.argv
process.env Provides access to environment variables. process.env.NODE_ENV
process.pid Returns the process identifier. process.pid
process.exitCode Sets the exit status to be used when the process exits. process.exitCode = 1

2. How the Process Object Works

When a Node.js application starts, Node.js creates a process context. The process object exposes information about that running instance to the JavaScript program.

Execute JavaScript File
node app.js
↓
Node.js Process Starts
↓
Access the process Object
↓
Read Runtime Information
Version, Platform, Arguments, Environment
↓
Use the Information in the Application

For example, an application can read its environment configuration or examine command-line arguments before performing a task.

3. Check the Node.js Version

The process.version property returns the version of Node.js running the application. It is useful when checking which runtime version is executing a program.

Example

version.js
console.log("Node.js Version:", process.version);

Execute the Program

Terminal
node version.js

Example Output

Node.js Version: v22.x.x

The exact version depends on the Node.js installation on your computer. The output above is only an illustrative example.

4. Check Platform and Architecture

Node.js provides properties that identify the operating system platform and the CPU architecture used by the Node.js executable.

Example

systemInfo.js
console.log("Platform:", process.platform);
console.log("Architecture:", process.arch);

Execute the Program

Terminal
node systemInfo.js

Example Output on a Typical 64-bit Windows System

Platform: win32
Architecture: x64

Explanation

  • process.platform commonly returns win32 on Windows, even on 64-bit Windows systems.
  • process.arch commonly returns x64 for a 64-bit x86 Node.js executable.
  • The actual values depend on the operating system and Node.js build.

5. Understand process.cwd()

The process.cwd() method returns the current working directory of the running process. This is the directory from which the application was launched, not necessarily the folder where the JavaScript file is stored.

Example

directory.js
console.log("Current Working Directory:");
console.log(process.cwd());

Execute the Program

Terminal
node directory.js

Example Output

Current Working Directory:
C:\Projects\NodeJsPractice

Your output will show the actual directory from which the command was executed.

Practical Use: The current working directory can help when an application needs to resolve relative file paths. Remember that relative paths are generally resolved against the working directory unless your code uses a different base path.

6. Understand process.pid

Every running operating-system process has a process identifier, commonly called a PID. The process.pid property returns the identifier assigned to the current Node.js process.

Example

processId.js
console.log("Application Name: CIIT Node.js Practice");
console.log("Process ID:", process.pid);

Execute the Program

Terminal
node processId.js

Example Output

Application Name: CIIT Node.js Practice
Process ID: 12345

The number 12345 is an example only. Your process identifier will usually be different each time you run the program.

7. Read Command-Line Arguments

The process.argv property contains an array of command-line arguments passed to the Node.js process. In a typical invocation, the first two entries identify the Node.js executable and the JavaScript file. Additional entries contain the arguments supplied by the user.

Example

student.js
const studentName = process.argv[2];
const courseName = process.argv[3];

console.log("Student Name:", studentName);
console.log("Course Name:", courseName);

Execute the Program with Arguments

Terminal
node student.js Samadhan Node.js

Expected Output

Student Name: Samadhan
Course Name: Node.js

How process.argv Works

Index Value in This Example Meaning
process.argv[0] Node.js executable path Identifies the Node.js executable.
process.argv[1] student.js path Identifies the executed script.
process.argv[2] Samadhan First user-supplied argument.
process.argv[3] Node.js Second user-supplied argument.
Important: If an argument is not supplied, its array entry may be undefined. Real applications should validate required arguments before using them.

8. Access Environment Variables

Environment variables provide configuration values to an application from outside its source code. They are commonly used to select an application mode or configure runtime behavior.

Node.js exposes environment variables through process.env. Their values are generally represented as strings, so numeric values may need conversion before mathematical operations.

Example: Read an Environment Variable

environment.js
const environment = process.env.APP_MODE || "development";

console.log("Application Mode:", environment);

Run Without Setting the Variable

Terminal
node environment.js

Expected Output When APP_MODE Is Not Set

Application Mode: development

Set the Variable on Windows PowerShell

PowerShell
$env:APP_MODE="production"
node environment.js

Expected Output

Application Mode: production

The PowerShell variable is set for the current session. Other shells use different commands to set environment variables.

Security Tip: Do not print passwords, access tokens, or other secrets from environment variables in application logs. Keep sensitive configuration protected.

9. Understand the Process Lifecycle

A Node.js process starts when the application is launched. It executes code and remains active while there is work that keeps the event loop running. When the process exits, Node.js provides an exit event that can be used for limited synchronous cleanup or final reporting.

Start Node.js Application
↓
Execute JavaScript
↓
Process Requests and Scheduled Work
↓
No More Work Keeping the Event Loop Active
↓
Process Exits

Example: Listen for the Exit Event

exitExample.js
process.on("exit", (code) => {
    console.log("Process is exiting.");
    console.log("Exit Code:", code);
});

console.log("Application is running.");

Execute the Program

Terminal
node exitExample.js

Expected Output

Application is running.
Process is exiting.
Exit Code: 0

In this simple program, no timer, server, or other active work keeps the process running, so it exits after the synchronous statements finish.

Important: Exit-event listeners must perform synchronous operations only. Asynchronous work scheduled inside an exit listener will not keep the process alive to complete that work.

10. Understand process.exitCode

The process.exitCode property sets the exit status that Node.js will use when the process exits naturally. By convention, exit code 0 indicates success, while a non-zero code usually indicates an error or unsuccessful execution.

Example: Set an Exit Code

exitCode.js
const studentName = "Samadhan";

if (studentName) {
    console.log("Student data processed successfully.");
    process.exitCode = 0;
} else {
    console.error("Student name is missing.");
    process.exitCode = 1;
}

Execute the Program

Terminal
node exitCode.js

Expected Output

Student data processed successfully.

This example sets the exit status based on a simple condition. In automated scripts and CI/CD pipelines, exit codes can help determine whether a command succeeded.

Best Practice: Prefer setting process.exitCode when you want Node.js to exit naturally. Calling process.exit() terminates the process immediately and may interrupt pending asynchronous operations.

11. Practical Example: Student Information

Let us combine multiple process properties and command-line arguments in one practical program.

Create studentInfo.js

studentInfo.js
const studentName = process.argv[2];
const courseName = process.argv[3];

console.log("Student Information");
console.log("-------------------");

console.log("Student:", studentName || "Not provided");
console.log("Course:", courseName || "Not provided");
console.log("Node.js Version:", process.version);
console.log("Operating Platform:", process.platform);
console.log("Process ID:", process.pid);

Run the Program

Terminal
node studentInfo.js Pradnya ".NET Full Stack"

Example Output

Student Information
-------------------
Student: Pradnya
Course: .NET Full Stack
Node.js Version: v22.x.x
Operating Platform: win32
Process ID: 12345

The Node.js version, platform, and process ID shown above are illustrative. Your computer will display its actual values.

What This Program Demonstrates

  • Reads the student name from process.argv.
  • Reads the course name, including a value containing spaces.
  • Displays the installed Node.js version.
  • Displays the operating-system platform.
  • Displays the current process identifier.

12. Common Mistakes with the Process Object

Mistake Reason Solution
Assuming a fixed Node.js version Different computers may use different installations. Check process.version.
Using an incorrect argument index User arguments begin after the executable and script entries. Check the required process.argv index.
Assuming a fixed working directory The program can be launched from different directories. Inspect process.cwd().
Expecting environment variables to exist A variable may not be configured in the current shell. Validate values from process.env.
Calling process.exit() unnecessarily Immediate termination may interrupt pending work. Use process.exitCode when appropriate.

13. CIIT Training Institute - Practice Task

Task: Build a Student Runtime Information Program

Create a file named studentRuntime.js and complete the following activities:

  1. Read a student name from command-line arguments.
  2. Read a course name from command-line arguments.
  3. Display the Node.js version.
  4. Display the current working directory.
  5. Display the operating-system platform.
  6. Display the process ID.
  7. Handle missing student or course arguments.
Sample Solution
studentRuntime.js
const studentName = process.argv[2];
const courseName = process.argv[3];

if (!studentName || !courseName) {
    console.error(
        "Usage: node studentRuntime.js <studentName> <courseName>"
    );

    process.exitCode = 1;
} else {
    console.log("CIIT TRAINING INSTITUTE");
    console.log("Student:", studentName);
    console.log("Course:", courseName);
    console.log("Node.js Version:", process.version);
    console.log("Working Directory:", process.cwd());
    console.log("Platform:", process.platform);
    console.log("Process ID:", process.pid);
}
Run the Program
Terminal
node studentRuntime.js Samadhan "Node.js"
Expected Output Format
CIIT TRAINING INSTITUTE
Student: Samadhan
Course: Node.js
Node.js Version: [your Node.js version]
Working Directory: [your project directory]
Platform: [your operating system]
Process ID: [current process ID]

The values in square brackets will be replaced by actual runtime information from your computer.

Summary

The Node.js process object provides information and controls for the currently running application. We learned how to inspect the Node.js version, operating platform, architecture, working directory, and process ID. We also used command-line arguments, environment variables, process exit events, and exit codes in practical programs. These concepts help students at CIIT TRAINING INSTITUTE understand how Node.js applications interact with their runtime environment and prepare for the next topic: Command-Line Arguments.