# Node.js – Introduction & How Node.js Works

# 🔹 What Is Node.js?

Node.js is a JavaScript runtime that allows JavaScript to run **outside the browser**.

Normally, JavaScript is associated with browsers:

```text
Chrome
Firefox
Edge
Safari
   ↓
JavaScript
```

Node.js allows us to run JavaScript directly on the operating system:

```text
Computer
   ↓
Node.js
   ↓
JavaScript
```

This means we can use JavaScript for:

```text
Frontend
+
Backend
+
APIs
+
CLI tools
+
Servers
+
Automation
```

That's one of the reasons Node.js became so important for full-stack JavaScript development.

* * *

# 🔹 JavaScript vs Node.js

This distinction is important.

### JavaScript

JavaScript is the programming language.

### Node.js

Node.js is a runtime environment that executes JavaScript outside the browser.

Think:

```text
JavaScript
    ↓
Programming Language

Node.js
    ↓
Runtime Environment
```

Node.js doesn't create a new programming language.

You are still writing JavaScript.

* * *

# 🔹 Why Was Node.js Created?

JavaScript was originally designed primarily for running inside browsers.

Developers eventually wanted to use JavaScript for server-side programming too.

Node.js made this possible by allowing JavaScript to run using the **V8 JavaScript engine** outside the browser.

This opened the door to:

```text
JavaScript
     ↓
Server-side applications
     ↓
Backend development
```

* * *

# 🔹 Node.js Uses Google's V8 Engine

Node.js uses Google's **V8 JavaScript engine**.

V8 is the engine used by Chromium-based browsers such as Chrome.

Conceptually:

```text
JavaScript Code
      ↓
     V8
      ↓
Machine Instructions
```

Node.js provides additional capabilities around the JavaScript engine, such as:

```text
File System
Networking
HTTP
Processes
Operating System APIs
Modules
```

This is what makes Node.js useful for backend development.

* * *

# 🔹 Browser JavaScript vs Node.js

There are some important differences.

| Browser JavaScript | Node.js |
| --- | --- |
| Runs in browser | Runs outside browser |
| Has DOM APIs | No browser DOM by default |
| Can manipulate HTML | Can work with filesystem |
| `window` available | `window` unavailable by default |
| Browser APIs | Node.js APIs |
| Mainly UI interactions | Backend/server-side tasks |

For example:

Browser:

```js
document.querySelector("h1");
```

Node.js doesn't have a browser DOM.

Instead, Node.js gives us APIs such as:

```js
fs
http
path
process
```

* * *

# 🔹 Installing Node.js

First, Node.js needs to be installed on the system.

After installation, open your terminal and check:

```bash
node --version
```

or:

```bash
node -v
```

You should get a version such as:

```text
v22.x.x
```

The exact version depends on what is currently installed.

Also check npm:

```bash
npm -v
```

* * *

# 🔹 What Is npm?

npm stands for **Node Package Manager**.

It is used to:

```text
Install packages
Manage dependencies
Run scripts
Publish packages
```

For example:

```bash
npm install express
```

This installs Express into your project.

* * *

# 🔹 Node.js REPL

Node.js provides an interactive environment called the **REPL**.

REPL stands for:

```text
Read
Evaluate
Print
Loop
```

Run:

```bash
node
```

Now you can directly write JavaScript:

```js
> 10 + 20
30
```

Try:

```js
> const name = "Saurabh"
> name
'Saurabh'
```

You can also execute JavaScript:

```js
> Math.max(10, 20, 30)
30
```

To exit:

```text
.exit
```

Or press:

```text
Ctrl + C
```

twice.

* * *

# 🔹 Running a JavaScript File With Node

Create:

```text
app.js
```

Add:

```js
console.log("Hello from Node.js");
```

Run:

```bash
node app.js
```

Output:

```text
Hello from Node.js
```

This is your first JavaScript program running outside the browser.

* * *

# 🔹 `console.log()` Still Works

The JavaScript you're already familiar with continues to work.

```js
const name = "Saurabh";

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

Run:

```bash
node app.js
```

Output:

```text
Hello Saurabh
```

This is important because your JavaScript knowledge directly carries over into Node.js.

* * *

# 🔹 The `process` Object

Node.js provides a global object called:

```js
process
```

It contains information about the currently running Node.js process.

For example:

```js
console.log(process.version);
```

You can also access command-line arguments:

```js
console.log(process.argv);
```

Running:

```bash
node app.js hello
```

will provide command-line information through `process.argv`.

* * *

# 🔹 Environment Variables

Node.js applications frequently use environment variables.

For example:

```text
PORT=5000
```

You can access it using:

```js
console.log(process.env.PORT);
```

This becomes extremely important later for:

```text
Database URLs
API keys
JWT secrets
Port numbers
Environment configuration
```

Sensitive values should not be hard-coded directly into source code.

* * *

# 🔹 Node.js Modules

One of the most important Node.js concepts is the **module system**.

Instead of putting everything into one giant file, we can divide our application into modules.

For example:

```text
project/
│
├── app.js
├── user.js
└── database.js
```

Each file can contain its own functionality.

This makes applications easier to maintain.

* * *

# 🔹 CommonJS Modules

Node.js historically used the CommonJS module system.

Example:

```js
// math.js

function add(a, b) {
  return a + b;
}

module.exports = add;
```

Then:

```js
// app.js

const add = require("./math");

console.log(add(10, 20));
```

Output:

```text
30
```

* * *

# 🔹 ES Modules

Modern Node.js also supports ES Modules.

Example:

```js
// math.js

export function add(a, b) {
  return a + b;
}
```

Then:

```js
// app.js

import { add } from "./math.js";

console.log(add(10, 20));
```

This syntax should already feel familiar because you've used imports and exports in React.

For modern projects, you'll commonly encounter ES module syntax.

* * *

# 🔹 Built-in Node.js Modules

Node.js comes with many built-in modules.

Some important ones:

```text
fs
path
http
os
url
events
crypto
```

You don't need to install these separately.

* * *

# 🔹 The `fs` Module

`fs` stands for **File System**.

It allows Node.js to interact with files.

Example:

```js
import fs from "fs";

fs.writeFileSync(
  "message.txt",
  "Hello from Node.js"
);
```

This creates:

```text
message.txt
```

with:

```text
Hello from Node.js
```

Node.js can therefore interact with the filesystem in ways browser JavaScript normally cannot.

* * *

# 🔹 Reading a File

```js
import fs from "fs";

const data = fs.readFileSync(
  "message.txt",
  "utf-8"
);

console.log(data);
```

Output:

```text
Hello from Node.js
```

* * *

# 🔹 Synchronous vs Asynchronous Operations

This is where Node.js becomes particularly interesting.

Synchronous code:

```js
const data = fs.readFileSync(
  "message.txt",
  "utf-8"
);
```

The program waits for the operation to finish.

Conceptually:

```text
Start
 ↓
Read file
 ↓
Wait
 ↓
Continue
```

Asynchronous code allows other work to continue while waiting for the operation.

For example:

```js
import fs from "fs";

fs.readFile(
  "message.txt",
  "utf-8",
  (error, data) => {
    if (error) {
      console.error(error);
      return;
    }

    console.log(data);
  }
);

console.log("This may execute before the file is read.");
```

This concept is extremely important for Node.js.

* * *

# 🔥 Node.js and Asynchronous Programming

Node.js is designed around asynchronous, non-blocking operations.

Imagine a server receives:

```text
Request A
Request B
Request C
```

Instead of unnecessarily waiting for one slow operation before handling everything else, Node.js can continue processing other work while an asynchronous operation is waiting.

Conceptually:

```text
Request
  ↓
Start operation
  ↓
Waiting...
  ↓
Continue other work
  ↓
Operation completes
  ↓
Callback / Promise
  ↓
Continue processing
```

This is one of the fundamental ideas behind Node.js.

* * *

# 🔹 Event-Driven Architecture

Node.js heavily uses an **event-driven architecture**.

Imagine:

```text
User Request
     ↓
Event
     ↓
Handler
     ↓
Response
```

Node.js applications constantly react to events such as:

```text
HTTP requests
File operations
Timers
Network activity
Streams
Connections
```

This model is closely connected to asynchronous programming.

* * *

# 🔹 What Is the Event Loop?

The event loop is one of the most important concepts in Node.js.

A simplified model:

```text
JavaScript Code
      ↓
Call Stack
      ↓
Async Operation
      ↓
Node.js / OS
      ↓
Task becomes ready
      ↓
Event Loop
      ↓
Call Stack
```

The event loop helps Node.js coordinate asynchronous operations.

You don't need to master the internal implementation today.

But you should understand this:

> **Node.js can handle asynchronous work without blocking JavaScript execution while that work is waiting.**

* * *

# 🔹 Promises in Node.js

Since you've already learned modern JavaScript, Promises should feel familiar.

Example:

```js
const getData = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("Data received");
    }, 2000);
  });
};

getData().then(data => {
  console.log(data);
});
```

Or using `async/await`:

```js
async function main() {
  const data = await getData();

  console.log(data);
}

main();
```

Your JavaScript knowledge is now directly useful on the backend.

* * *

# 🔹 Creating a Node Project

Instead of manually creating everything, we can initialize an npm project.

Run:

```bash
npm init
```

Or:

```bash
npm init -y
```

This creates:

```text
package.json
```

* * *

# 🔹 What Is `package.json`?

`package.json` contains important project information.

For example:

```json
{
  "name": "my-node-app",
  "version": "1.0.0",
  "main": "app.js"
}
```

It can also contain:

```text
Dependencies
Scripts
Project metadata
Module configuration
```

For example:

```json
{
  "scripts": {
    "start": "node app.js"
  }
}
```

Then:

```bash
npm start
```

runs:

```bash
node app.js
```

* * *

# 🔹 Installing a Package

Suppose we want Express.

```bash
npm install express
```

npm will add Express as a dependency.

Your project now contains:

```text
node_modules/
package.json
package-lock.json
```

* * *

# 🔹 What Is `node_modules`?

`node_modules` contains installed packages and their dependencies.

For example:

```text
node_modules/
    ├── express/
    ├── ...
    └── ...
```

You generally **don't manually edit this folder**.

It is generated from your package dependencies.

* * *

# 🔹 What Is `package-lock.json`?

When npm installs dependencies, it creates:

```text
package-lock.json
```

It records the resolved dependency versions and related installation information.

This helps make dependency installation more reproducible across environments.

* * *

# 🔹 Your First Node Project

Create:

```text
node-backend/
│
├── package.json
└── app.js
```

Initialize:

```bash
npm init -y
```

Create:

```js
// app.js

console.log("My first Node.js backend");
```

Run:

```bash
node app.js
```

Output:

```text
My first Node.js backend
```

You've officially started the backend side of your journey.

* * *

# 🔹 Why Node.js Is Important for MERN

The MERN stack is:

```text
M → MongoDB
E → Express.js
R → React
N → Node.js
```

Your journey so far:

```text
HTML
 ↓
CSS
 ↓
JavaScript
 ↓
React
```

Now:

```text
React
  +
Node.js
  +
Express.js
  +
MongoDB
  ↓
MERN
```

Node.js provides the runtime for the backend.

Express will make building HTTP APIs easier.

MongoDB will provide the database layer.

* * *

# 🔥 The Bigger Picture

Eventually, your application will look something like:

```text
                 USER
                   ↓
                React
                   ↓
              HTTP Request
                   ↓
              Express API
                   ↓
             Node.js Runtime
                   ↓
              Business Logic
                   ↓
               MongoDB
                   ↓
              Response
                   ↓
                React
                   ↓
                  UI
```

Today we're only beginning to understand the Node.js layer.
