Skip to main content

Command Palette

Search for a command to run...

Node.js โ€“ Introduction & How Node.js Works

Updated
โ€ข9 min readโ€ขView as Markdown

๐Ÿ”น What Is Node.js?

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

Normally, JavaScript is associated with browsers:

Chrome
Firefox
Edge
Safari
   โ†“
JavaScript

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

Computer
   โ†“
Node.js
   โ†“
JavaScript

This means we can use JavaScript for:

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:

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:

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:

JavaScript Code
      โ†“
     V8
      โ†“
Machine Instructions

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

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:

document.querySelector("h1");

Node.js doesn't have a browser DOM.

Instead, Node.js gives us APIs such as:

fs
http
path
process

๐Ÿ”น Installing Node.js

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

After installation, open your terminal and check:

node --version

or:

node -v

You should get a version such as:

v22.x.x

The exact version depends on what is currently installed.

Also check npm:

npm -v

๐Ÿ”น What Is npm?

npm stands for Node Package Manager.

It is used to:

Install packages
Manage dependencies
Run scripts
Publish packages

For example:

npm install express

This installs Express into your project.


๐Ÿ”น Node.js REPL

Node.js provides an interactive environment called the REPL.

REPL stands for:

Read
Evaluate
Print
Loop

Run:

node

Now you can directly write JavaScript:

> 10 + 20
30

Try:

> const name = "Saurabh"
> name
'Saurabh'

You can also execute JavaScript:

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

To exit:

.exit

Or press:

Ctrl + C

twice.


๐Ÿ”น Running a JavaScript File With Node

Create:

app.js

Add:

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

Run:

node app.js

Output:

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.

const name = "Saurabh";

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

Run:

node app.js

Output:

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:

process

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

For example:

console.log(process.version);

You can also access command-line arguments:

console.log(process.argv);

Running:

node app.js hello

will provide command-line information through process.argv.


๐Ÿ”น Environment Variables

Node.js applications frequently use environment variables.

For example:

PORT=5000

You can access it using:

console.log(process.env.PORT);

This becomes extremely important later for:

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:

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:

// math.js

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

module.exports = add;

Then:

// app.js

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

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

Output:

30

๐Ÿ”น ES Modules

Modern Node.js also supports ES Modules.

Example:

// math.js

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

Then:

// 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:

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:

import fs from "fs";

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

This creates:

message.txt

with:

Hello from Node.js

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


๐Ÿ”น Reading a File

import fs from "fs";

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

console.log(data);

Output:

Hello from Node.js

๐Ÿ”น Synchronous vs Asynchronous Operations

This is where Node.js becomes particularly interesting.

Synchronous code:

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

The program waits for the operation to finish.

Conceptually:

Start
 โ†“
Read file
 โ†“
Wait
 โ†“
Continue

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

For example:

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:

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:

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:

User Request
     โ†“
Event
     โ†“
Handler
     โ†“
Response

Node.js applications constantly react to events such as:

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:

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:

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

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

Or using async/await:

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:

npm init

Or:

npm init -y

This creates:

package.json

๐Ÿ”น What Is package.json?

package.json contains important project information.

For example:

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

It can also contain:

Dependencies
Scripts
Project metadata
Module configuration

For example:

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

Then:

npm start

runs:

node app.js

๐Ÿ”น Installing a Package

Suppose we want Express.

npm install express

npm will add Express as a dependency.

Your project now contains:

node_modules/
package.json
package-lock.json

๐Ÿ”น What Is node_modules?

node_modules contains installed packages and their dependencies.

For example:

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:

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:

node-backend/
โ”‚
โ”œโ”€โ”€ package.json
โ””โ”€โ”€ app.js

Initialize:

npm init -y

Create:

// app.js

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

Run:

node app.js

Output:

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:

M โ†’ MongoDB
E โ†’ Express.js
R โ†’ React
N โ†’ Node.js

Your journey so far:

HTML
 โ†“
CSS
 โ†“
JavaScript
 โ†“
React

Now:

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:

                 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.

2 views

100 Days of Code: My Journey to Becoming a Full Stack Developer

Part 1 of 50

Welcome to my 100 Days of Code journey! In this series, I'll document my daily progress as I learn Full Stack Web Development from the ground up. Every post will cover what I learned, challenges I faced, mistakes I made, and the projects I built. My goal is not just to complete 100 days but to become a better developer through consistency, discipline, and learning in public. Topics I'll cover include: โ€ข Git & GitHub โ€ข HTML, CSS & JavaScript โ€ข React.js โ€ข Node.js & Express โ€ข MongoDB โ€ข APIs โ€ข Real-world Projects โ€ข AI tools for Developers Whether you're just starting out or revising your fundamentals, I hope this journey helps you learn alongside me. Let's build, learn, and grow together! ๐Ÿš€