0% found this document useful (0 votes)
14 views24 pages

Introduction to Node.js Basics

Node.js is a runtime environment that enables JavaScript to run outside the browser, utilizing Google's V8 engine and providing built-in APIs for server-side applications. It features non-blocking I/O, a single-threaded event loop, and a vast ecosystem through NPM, making it ideal for web servers and real-time applications. The document covers installation, core concepts like modules, file system operations, events, streams, and creating HTTP servers.

Uploaded by

divyanshivats27
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views24 pages

Introduction to Node.js Basics

Node.js is a runtime environment that enables JavaScript to run outside the browser, utilizing Google's V8 engine and providing built-in APIs for server-side applications. It features non-blocking I/O, a single-threaded event loop, and a vast ecosystem through NPM, making it ideal for web servers and real-time applications. The document covers installation, core concepts like modules, file system operations, events, streams, and creating HTTP servers.

Uploaded by

divyanshivats27
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

NODEJS

Favorite

Status Inbox

Notebooks BACKEND

Created @September 5, 2025

Edited @September 5, 2025 5:14 PM

Archive

Pin

🌱 What is [Link]?
[Link] is a runtime environment that allows you to run JavaScript outside
the browser.

Normally, JavaScript runs only inside browsers (like Chrome, Firefox).

[Link] uses Google’s V8 JavaScript engine to execute JS code on your


system.

It also provides built-in APIs (like file system, networking, streams, events,
etc.) so you can build server-side applications.

👉 In short:
[Link] = JavaScript + V8 engine + C++ bindings + built-in APIs

⚡ Why use [Link]?


Non-blocking I/O → handles thousands of requests efficiently.

Single-threaded event loop → uses events instead of threads.

Huge ecosystem → NPM (Node Package Manager) has millions of libraries.

Perfect for web servers, APIs, real-time apps (chat, live updates),
streaming apps.

NODEJS 1
📂 Step 1: Install & Setup
1. Install [Link] from [Link]

2. Verify installation:

node -v
npm -v

This gives [Link] and NPM versions.

3. Run your first Node script:

node
> [Link]("Hello from [Link]!");

4. Or create a file [Link] :

[Link]("Hello World from [Link]");

Run:

node [Link]

📖 Step 2: Core Concepts


We’ll cover these in order:

1. Modules & require()

2. File System (fs)

3. Events & EventEmitter

4. Streams

5. HTTP module (building a server)

NODEJS 2
6. Asynchronous programming (callbacks, promises, async/await)

7. NPM packages

8. [Link] (later – after core Node)

📦 [Link] Modules
🔹 What is a Module?
A module in [Link] is simply a reusable block of code.

Every file in [Link] is treated as a separate module.

Node has 3 types of modules:

1. Core Modules → built-in (like fs , http , path ).

2. Local Modules → your own custom files.

3. Third-party Modules → installed via npm (like lodash , express ).

🔹 Importing and Exporting Modules


Example 1: Creating Your Own Module
Create a file [Link] :

// [Link]
function add(a, b) {
return a + b;
}

function multiply(a, b) {
return a * b;
}

// Exporting functions

NODEJS 3
[Link] = { add, multiply };

Now create [Link] :

// [Link]
const math = require("./math");

[Link]([Link](2, 3)); // 5
[Link]([Link](4, 6)); // 24

Run:

node [Link]

✅ This is how you export and import custom modules.


Example 2: Importing Only One Function

// [Link]
[Link] = (a, b) => a + b;
[Link] = (a, b) => a * b;

// [Link]
const { add } = require("./math");

[Link](add(10, 20)); // 30

🔹 Core Modules (built-in)


Node comes with built-in modules.
Example: path module

NODEJS 4
const path = require("path");

[Link](__filename); // full path of current file


[Link](__dirname); // directory name
[Link]([Link](__filename)); // just file name
[Link]([Link](__filename)); // extension

Example: os module

const os = require("os");

[Link]([Link]()); // e.g. Windows_NT


[Link]([Link]()); // win32
[Link]([Link]()); // free memory
[Link]([Link]()); // total memory

🔹 ES Modules (Modern Way)


By default, Node uses CommonJS ( require , [Link] ).
But you can also use ESM ( import , export ), if you:

1. Add "type": "module" in [Link] , or

2. Use .mjs extension.

Example:

// [Link]
export function add(a, b) {
return a + b;
}

// [Link]
import { add } from "./[Link]";

NODEJS 5
[Link](add(5, 7));

✨ So, modules allow you to organize code into smaller, reusable pieces.

📂 File System (fs) Module in [Link]


The fs module allows us to work with the file system on our computer:

Create files

Read files

Write/update files

Delete files

👉 It has two types of methods:


1. Synchronous (blocking) → executes line by line, waits until task finishes.

2. Asynchronous (non-blocking) → executes in background, uses


callbacks/promises.

🔹 Importing fs
const fs = require("fs");

1️⃣ Reading Files


Asynchronous (preferred):

const fs = require("fs");

[Link]("[Link]", "utf8", (err, data) => {

NODEJS 6
if (err) {
[Link]("Error reading file:", err);
return;
}
[Link]("File content:", data);
});

Synchronous:

const data = [Link]("[Link]", "utf8");


[Link]("File content:", data);

2️⃣ Writing Files


Asynchronous:

[Link]("[Link]", "Hello, [Link]!", (err) => {


if (err) throw err;
[Link]("File written successfully!");
});

Synchronous:

[Link]("[Link]", "This is sync write.");

3️⃣ Appending to a File


[Link]("[Link]", "\nAppended content!", (err) => {
if (err) throw err;
[Link]("Content appended!");

NODEJS 7
});

4️⃣ Deleting a File


[Link]("[Link]", (err) => {
if (err) throw err;
[Link]("File deleted!");
});

5️⃣ Creating a Folder


[Link]("newFolder", (err) => {
if (err) throw err;
[Link]("Folder created!");
});

6️⃣ Reading a Folder


[Link](".", (err, files) => {
if (err) throw err;
[Link]("Files in directory:", files);
});

✅ Summary:
readFile , writeFile , appendFile , unlink → work with files

mkdir , readdir → work with directories

NODEJS 8
⚡ Events & EventEmitter in [Link]
🔹 Why Events?
[Link] is event-driven.

Instead of waiting for tasks (like file reads, network requests), Node listens
for events and executes callbacks.

Example:

A file is read → Node emits a "data" event.

An HTTP request comes → Node emits a "request" event.

At the heart of this system is the EventEmitter class (from Node’s events

module).

🔹 Using EventEmitter
Step 1: Import events

const EventEmitter = require("events");

Step 2: Create an emitter object

const emitter = new EventEmitter();

Step 3: Register (listen to) an event

[Link]("greet", () => {
[Link]("Hello! An event was triggered.");
});

NODEJS 9
Step 4: Emit (trigger) the event

[Link]("greet");
// Output: Hello! An event was triggered.

🔹 Passing Data with Events


const EventEmitter = require("events");
const emitter = new EventEmitter();

[Link]("greet", (name) => {


[Link](`Hello, ${name}!`);
});

[Link]("greet", "Divyanshi");
// Output: Hello, Divyanshi!

🔹 Multiple Listeners
[Link]("order", (item) => {
[Link](`Order received for ${item}`);
});

[Link]("order", (item) => {


[Link](`Cooking ${item}...`);
});

[Link]("order", "Pizza");

// Output:
// Order received for Pizza
// Cooking Pizza...

NODEJS 10
🔹 Built-in Events
Many Node core modules use EventEmitter:

fs → streams emit "data" , "end" , "error" .

http → server emits "request" .

Example:

const http = require("http");

const server = [Link]();

[Link]("request", (req, res) => {


[Link]("Hello, World!");
[Link]();
});

[Link](3000, () => [Link]("Server running on port 3000"));

✅ Summary:
EventEmitter lets you subscribe (on) and emit (trigger) events.

This is how Node handles async, non-blocking operations.

🌊 Streams in [Link]
🔹 What is a Stream?
A stream is like a pipe — it lets you read or write data in chunks, instead of
loading the whole thing at once.

Example: Reading a 10GB video file

[Link]() → loads entire file into memory ( 💥 crash).


NODEJS 11
[Link]() → reads little by little (64KB chunks by default).

👉 Streams are event-based (built on EventEmitter ).

🔹 Types of Streams
1. Readable → for reading data ( [Link] )

2. Writable → for writing data ( [Link] )

3. Duplex → both read & write (e.g. TCP sockets)

4. Transform → modifies data while streaming (e.g. compress, encrypt)

1️⃣ Reading a File with a Readable Stream


const fs = require("fs");

const readStream = [Link]("./[Link]", "utf8");

[Link]("data", (chunk) => {


[Link]("New Chunk Received:");
[Link](chunk);
});

[Link]("end", () => {
[Link]("Finished reading file.");
});

[Link]("error", (err) => {


[Link]("Error:", err);
});

👉 Output will show chunks of the file, not the entire file at once.
2️⃣ Writing to a File with a Writable Stream
const fs = require("fs");

NODEJS 12
const writeStream = [Link]("./[Link]");

[Link]("Hello, this is the first line.\n");


[Link]("And here’s another line.\n");
[Link]();

[Link]("finish", () => {
[Link]("All data written to file.");
});

3️⃣ Piping (Connecting Readable → Writable)


Instead of manually listening for data and writing, we can use .pipe() :

const fs = require("fs");

const readStream = [Link]("./[Link]", "utf8");


const writeStream = [Link]("./[Link]");

[Link](writeStream);

[Link]("File is being copied...");

👉 Super efficient way to copy files.


4️⃣ Transform Streams (Example: Compression)
const fs = require("fs");
const zlib = require("zlib");

const readStream = [Link]("[Link]");


const writeStream = [Link]("[Link]");

const gzip = [Link]();

NODEJS 13
[Link](gzip).pipe(writeStream);

[Link]("File compressed successfully!");

✅ Summary:
Streams = data in chunks (not full memory).

Use readStream , writeStream , .pipe() .

Transform streams can compress, encrypt, etc.

🔹 1. What is .pipe() ?
Think of a pipe in real life (water flowing through a pipe).

You connect a source (tap) to a destination (bucket).

Water flows directly without you holding a cup again and again.

In [Link]:

readStream = source (tap)

writeStream = destination (bucket)

.pipe() connects them directly.

Without .pipe() (manual way)

const fs = require("fs");

const readStream = [Link]("[Link]", "utf8");


const writeStream = [Link]("[Link]");

[Link]("data", (chunk) => {


[Link](chunk);
});

[Link]("end", () => {
[Link]("File copied manually.");

NODEJS 14
});

👉 Here, you manually listen for "data" events and write chunks.

With .pipe() (automatic way)

const fs = require("fs");

const readStream = [Link]("[Link]", "utf8");


const writeStream = [Link]("[Link]");

[Link](writeStream);

[Link]("File is being copied using pipe...");

👉 .pipe() does the "data" + "end" handling automatically.


So instead of you carrying cups of water, the pipe carries everything.

🔹 2. What is Compression with Streams?


Compression is like squeezing a file into a smaller version (like zipping).
In [Link], the zlib module provides a Transform Stream:

It takes chunks in,

Compresses them,

Sends them out.

Example: Compressing a File

const fs = require("fs");
const zlib = require("zlib");

// Read from original file


const readStream = [Link]("[Link]");

NODEJS 15
// Create gzip transform stream
const gzip = [Link]();

// Write to compressed file


const writeStream = [Link]("[Link]");

// Connect them using pipe


[Link](gzip).pipe(writeStream);

[Link]("File compressed!");

👉 Flow:
[Link] → readStream → gzip (compress) → writeStream → [Link]

✅ Key Takeaways
.pipe() = connect source → transform(s) → destination.

Compression just adds a transform step in the pipeline.

You can even chain multiple transforms. Example: compress → encrypt →


write.

🌐 HTTP Module
The http module lets you:

Create a server

Handle requests & responses

Send HTML, JSON, files, etc.

Example: Basic Server

NODEJS 16
const http = require("http");

const server = [Link]((req, res) => {


// set response header
[Link](200, { "Content-Type": "text/plain" });
[Link]("Hello from [Link] server!");
});

[Link](3000, () => {
[Link]("Server running at [Link]
});

👉 Run it and visit [Link] in your browser.

Example: Routing

const http = require("http");

const server = [Link]((req, res) => {


if ([Link] === "/") {
[Link](200, { "Content-Type": "text/html" });
[Link]("<h1>Welcome Home!</h1>");
} else if ([Link] === "/about") {
[Link](200, { "Content-Type": "text/html" });
[Link]("<h1>About Page</h1>");
} else {
[Link](404, { "Content-Type": "text/html" });
[Link]("<h1>Page Not Found</h1>");
}
});

[Link](3000, () => {
[Link]("Server running at [Link]
});

NODEJS 17
✨ With just this, you can already serve web pages without Express.
Later we’ll also see handling JSON, query params, POST data, etc.

🖥️ OS Module
The os module provides information about the system.

Example

const os = require("os");

[Link]("OS Type:", [Link]()); // Windows_NT, Linux, etc.


[Link]("Platform:", [Link]()); // win32, linux, darwin
[Link]("CPU Architecture:", [Link]());
[Link]("Free Memory:", [Link]());
[Link]("Total Memory:", [Link]());
[Link]("Uptime (seconds):", [Link]());
[Link]("User Info:", [Link]());

👉 You can use this in monitoring tools, system dashboards, etc.


📂 Path Module
The path module helps you work with file and directory paths.

Example

const path = require("path");

const filePath = "C:/Users/Divyanshi/Desktop/NodeJs/[Link]";

[Link]("Base:", [Link](filePath)); // [Link]


[Link]("Dir:", [Link](filePath)); // C:/Users/Divyanshi/Desktop/
NodeJs

NODEJS 18
[Link]("Ext:", [Link](filePath)); // .txt
[Link]("Parse:", [Link](filePath)); // object with root, dir, base, e
xt, name
[Link]("Join:", [Link]("folder", "subfolder", "[Link]")); // folder/subfol
der/[Link]

👉 Very useful when you’re building servers, so you don’t hardcode paths.
✅ With these two, you now have all the basic utility modules ready.

⚙️ [Link] Architecture
1. Single-threaded Event Loop
[Link] is single-threaded (only one main thread runs JS code).

Instead of blocking, it uses an event loop to handle multiple requests


concurrently.

2. Components
1. V8 Engine

Converts JavaScript → machine code.

Super fast (same engine used by Chrome).

2. libuv

C library that provides an event loop & thread pool.

Handles async operations like file system, DNS, networking.

3. Event Loop

Heart of [Link].

Continuously checks the callback queue and executes pending tasks.

4. Thread Pool

NODEJS 19
Even though Node is single-threaded, some tasks (like file I/O, crypto,
compression) use worker threads behind the scenes.

3. How it Works
Let’s say you make 3 requests:

1. Request A → DB Query

2. Request B → File Read

3. Request C → Simple Calculation

🌀 Flow:
Request C is processed immediately on the main thread (non-blocking).

Request A & B are passed to libuv → executed in the background.

Once completed, their callbacks are placed in the event loop queue,
waiting for execution.

This way [Link] handles thousands of concurrent requests efficiently.

4. Architecture Diagram (simplified)

┌──────────────────────┐
│ Application Code │
└─────────┬────────────┘

┌─────▼─────┐
│ V8 JS │
│ Engine │
└─────┬─────┘

┌─────▼───────┐
│ libuv │
│ Event Loop │
└─────┬────────┘
┌─────────┼─────────┐
│ │ │
Thread Pool OS Calls Networking

NODEJS 20
5. Why [Link] is Good
✅ Non-blocking, event-driven → great for I/O heavy apps.
✅ Lightweight & fast (built on V8).
✅ Huge ecosystem (npm).
✅ Perfect for APIs, real-time apps, microservices.
6. Where [Link] Struggles
❌ Not ideal for CPU-intensive tasks (like image processing, ML).
❌ Since it's single-threaded, heavy computation can block other requests.
(But we can use worker threads or child processes if needed).

🌀 [Link] Event Loop (Deep Dive)


[Link] executes JS code on a single thread, but uses the event loop to
handle async tasks efficiently.

1. Call Stack, APIs & Callback Queue


Call Stack → Where synchronous code runs.

Node APIs → Handle async stuff (e.g., setTimeout , [Link] ).

Callback Queue → Stores callbacks waiting to be executed when stack is


free.

2. Event Loop Phases


The event loop runs in phases:

1. Timers Phase

Executes callbacks from setTimeout & setInterval .

NODEJS 21
2. Pending Callbacks Phase

Executes I/O callbacks that were deferred.

3. Idle, Prepare (internal)

4. Poll Phase

Retrieves new I/O events (e.g., network, file).

Executes I/O callbacks immediately if ready.

If none are pending → waits for them.

5. Check Phase

Executes setImmediate() callbacks.

6. Close Callbacks Phase

Executes close events like [Link]("close") .

3. Microtasks vs Macrotasks
Microtasks → Processed immediately after the current operation, before
next event loop phase.
Examples:

[Link]() (Node specific, runs before microtasks queue)

Promises ( .then , catch )

Macrotasks → Handled in phases of event loop.


Examples:

setTimeout , setInterval , setImmediate

4. Execution Order Example

setTimeout(() => [Link]("setTimeout"), 0);

setImmediate(() => [Link]("setImmediate"));

[Link]().then(() => [Link]("Promise"));

NODEJS 22
[Link](() => [Link]("nextTick"));

👉 Output will be:


nextTick
Promise
setTimeout
setImmediate

Why?

[Link]() runs before event loop continues.

Promises (microtasks) run right after that.

Then the event loop checks timers → runs setTimeout .

Finally setImmediate runs in the "check" phase.

5. Diagram of Execution Order

Call Stack → [Link] → Microtasks (Promises) → Event Loop (Pha


ses)

6. Interview Key Points


[Link] is single-threaded but can handle concurrency using the event
loop.

[Link]() always executes before Promises.

setTimeout(fn, 0) does not run immediately, it waits until the next event loop
tick.

runs after the poll phase, so it usually fires after


setImmediate() setTimeout(fn, 0)

but order can vary depending on context.

NODEJS 23
✅ With this, you now fully understand how async code works under the hood
in [Link].

NODEJS 24

You might also like