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 Global Objects

Learn about global objects in Node.js, understand console, global This, timers, and other commonly used APIs, and discover how these objects help developers execute JavaScript without importing every feature manually.

1. Introduction to Global Objects

Global objects and APIs are available in the JavaScript environment without requiring us to import them individually. Node.js provides several built-in globals that help developers print messages, schedule operations, access the current execution context, and work with application data.

For example, we can use console.log() directly in a JavaScript file to display a message in the terminal. We do not need to import the console object first.

Important Concept: A global API is available in the current runtime environment without an explicit import. Not every object or module in Node.js is global; many features must still be imported.

Common Node.js Globals

Global Purpose Example
console Displays messages and debugging information. console.log("Hello");
globalThis References the global object for the current JavaScript environment. globalThis.console
setTimeout() Schedules a callback to run after a delay. setTimeout(callback, 1000)
setInterval() Schedules a callback repeatedly. setInterval(callback, 1000)
clearTimeout() Cancels a pending timeout. clearTimeout(timerId)
clearInterval() Stops a repeating interval. clearInterval(timerId)
process Provides information and controls for the current Node.js process. process.version
Buffer Works with binary data. Buffer.from("CIIT")

2. How Global APIs Work

When Node.js executes a JavaScript file, the runtime provides access to its supported global APIs. The program can use these APIs directly where appropriate.

JavaScript File
app.js
↓
Node.js Runtime
↓
Available Global APIs
console, setTimeout(), globalThis
↓
Execute Operations and Display Results

Some APIs are provided by Node.js, while others are part of the JavaScript language or are available through the runtime. Their exact behavior depends on the API.

3. The Console Object

The console object provides methods for displaying information, warnings, errors, and debugging output. It is one of the most commonly used APIs when learning Node.js.

Example: Display Messages

consoleExample.js
console.log("Hello Samadhan!");
console.info("Pradnya is learning Node.js.");
console.warn("This is a warning message.");
console.error("This is an error message.");

Execute the Program

Terminal
node consoleExample.js

Expected Output

Hello Samadhan!
Pradnya is learning Node.js.
This is a warning message.
This is an error message.

Method Explanation

  • console.log() displays general information.
  • console.info() displays informational messages.
  • console.warn() displays a warning.
  • console.error() displays an error message.
Note: Terminal styling and whether warnings or errors appear differently can depend on the terminal. The important point is to understand the purpose of each method.

4. The globalThis Object

globalThis is the standard JavaScript way to reference the global object in the current environment. In Node.js, it provides access to global properties and APIs that are available in that environment.

Example: Access Console Through globalThis

globalExample.js
globalThis.console.log("Using globalThis in Node.js.");

console.log(
    globalThis === global
);

Execute the Program

Terminal
node globalExample.js

Expected Output in Standard Node.js

Using globalThis in Node.js.
true

Explanation

  • globalThis.console accesses the console property through the global object.
  • global is Node.js's traditional global-object reference.
  • In standard Node.js, globalThis and global reference the same global object.
Best Practice: Avoid adding unnecessary custom properties to the global object. Global variables can make code harder to maintain and may create naming conflicts.

5. The setTimeout() Function

setTimeout() schedules a callback to run after a specified delay. The delay is measured in milliseconds. The callback does not necessarily execute at the exact requested time; it runs when the event loop can process it.

Example: Display a Delayed Message

timeoutExample.js
console.log("Program started.");

setTimeout(() => {
    console.log("Hello Samadhan!");
}, 2000);

console.log("Program continues.");

Execute the Program

Terminal
node timeoutExample.js

Expected Output Order

Program started.
Program continues.
Hello Samadhan!

Explanation

  • The first message is printed immediately.
  • setTimeout() schedules the callback for approximately two seconds later.
  • The next synchronous statement runs without waiting for the timeout.
  • The callback runs later when the event loop can process it.
Remember: setTimeout() does not pause the entire JavaScript program for the specified delay. It schedules a callback.

6. The setInterval() Function

setInterval() schedules a callback to run repeatedly at a requested interval. It is useful for recurring tasks, although the actual timing can vary.

Example: Display a Message Three Times

intervalExample.js
let count = 0;

const timerId = setInterval(() => {
    count++;

    console.log("Samadhan's task count:", count);

    if (count === 3) {
        clearInterval(timerId);
        console.log("Task completed.");
    }
}, 1000);

Execute the Program

Terminal
node intervalExample.js

Expected Output

Samadhan's task count: 1
Samadhan's task count: 2
Samadhan's task count: 3
Task completed.

Code Explanation

  • count stores how many times the callback has run.
  • setInterval() schedules repeated execution.
  • timerId stores the identifier returned by the timer.
  • clearInterval(timerId) stops future interval callbacks.
Important: Always stop an interval when it is no longer required. An active timer can keep a Node.js process running.

7. The Buffer Global

A Buffer is used to work with binary data. Node.js applications commonly use buffers when processing file contents, network data, and other byte-based information.

Example: Convert Text into a Buffer

bufferExample.js
const message = "CIIT";

const bufferData = Buffer.from(message);

console.log("Original Text:", message);
console.log("Buffer Data:", bufferData);
console.log("Buffer Length:", bufferData.length);
console.log("Converted Text:", bufferData.toString());

Execute the Program

Terminal
node bufferExample.js

Expected Output

Original Text: CIIT
Buffer Data: <Buffer 43 49 49 54>
Buffer Length: 4
Converted Text: CIIT

Explanation

  • Buffer.from(message) creates a buffer from the text.
  • The buffer stores the UTF-8 bytes for this ASCII text.
  • bufferData.length returns the number of bytes.
  • toString() converts the buffer contents back to text.
Note: Buffer length measures bytes, not necessarily the number of characters. Some characters require multiple bytes in UTF-8.

8. Global APIs vs Imported Modules

Not all Node.js features are globally available. Some APIs, such as console and Buffer, are available globally, while other features are accessed through modules.

Feature How to Access Example
Console Global API console.log("Hello");
Buffer Global API Buffer.from("CIIT");
File System Import the fs module const fs = require("node:fs");
HTTP Server Import the http module const http = require("node:http");
Path Utilities Import the path module const path = require("node:path");

Example: Import the File System Module

moduleExample.js
const fs = require("node:fs");

console.log("File system module loaded.");
console.log(typeof fs.readFile);

Expected Output

File system module loaded.
function

The fs module is imported explicitly. Its readFile method is a function that can be used to read file contents.

9. Common Mistakes When Using Globals

Mistake Why It Happens Better Approach
Assuming every API is global Not all Node.js modules are global. Import required modules explicitly.
Leaving intervals active Repeated callbacks continue to be scheduled. Use clearInterval() when finished.
Expecting exact timer timing Callback execution depends on event-loop scheduling. Treat timer delays as minimum scheduling delays, not exact guarantees.
Adding too many global variables Global names can conflict and make code harder to maintain. Prefer local variables and module scope.
Confusing bytes with characters UTF-8 characters can require multiple bytes. Understand how Buffer length is measured.

10. CIIT Training Institute - Practice Task

Task: Create a Global APIs Demonstration

Create a file named globalPractice.js and complete these activities:

  1. Print a welcome message for Samadhan and Pradnya.
  2. Display the Node.js version using the process object.
  3. Convert the text CIIT into a Buffer.
  4. Display the buffer length.
  5. Schedule a message using setTimeout().
  6. Run the program and inspect its output.
Sample Solution
globalPractice.js
console.log("Hello Samadhan!");
console.log("Hello Pradnya!");

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

const instituteName = "CIIT";
const instituteBuffer = Buffer.from(instituteName);

console.log("Buffer Length:", instituteBuffer.length);

setTimeout(() => {
    console.log("Global APIs practice completed.");
}, 1000);
Expected Output
Hello Samadhan!
Hello Pradnya!
Node.js Version: [your Node.js version]
Buffer Length: 4
Global APIs practice completed.

The Node.js version will vary by computer. The delayed message appears after the synchronous statements have run.

Summary

Node.js global APIs provide useful functionality without requiring an explicit import for every feature. We learned how to use console methods, globalThis, setTimeout, setInterval, timer cancellation, and Buffer. We also compared globally available APIs with modules that must be imported. Practical examples at CIIT TRAINING INSTITUTE help students understand these concepts and prepare for the next topic: the Node.js Process Object.