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