Skip to main content

Node.js Introduction - Understanding the JavaScript Runtime

Node.js is a powerful JavaScript runtime environment that allows you to run JavaScript on the server side. Built on Chrome's V8 JavaScript engine, Node.js enables developers to build scalable network applications using JavaScript outside of web browsers.

What is Node.js?

Node.js is not a programming language, but rather a runtime environment that executes JavaScript code on the server. It was created by Ryan Dahl in 2009 and has since become one of the most popular platforms for building web applications.

Key Characteristics

  • Runtime Environment: Executes JavaScript outside the browser
  • Built on V8: Uses Google Chrome's V8 JavaScript engine
  • Event-Driven: Asynchronous, non-blocking I/O model
  • Single-Threaded: Uses a single main thread with event loop
  • Cross-Platform: Runs on Windows, macOS, and Linux
  • Open Source: Free and community-driven

Node.js Architecture

V8 JavaScript Engine

Node.js is built on V8, the same JavaScript engine that powers Google Chrome. V8 is responsible for:

  • Parsing JavaScript Code: Converting JavaScript into executable code
  • Compilation: Compiling JavaScript to machine code
  • Memory Management: Handling garbage collection and memory allocation
  • Optimization: Just-in-time (JIT) compilation for performance
// V8 engine optimizations
function calculateSum(numbers) {
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
return sum;
}

// V8 optimizes this function for better performance
console.log(calculateSum([1, 2, 3, 4, 5])); // 15

Event Loop

The Event Loop is the core of Node.js's asynchronous architecture:

// Event Loop Example
console.log('Start');

setTimeout(() => {
console.log('Timer 1');
}, 0);

setImmediate(() => {
console.log('Immediate 1');
});

process.nextTick(() => {
console.log('Next Tick 1');
});

console.log('End');

// Output:
// Start
// End
// Next Tick 1
// Timer 1
// Immediate 1

Non-Blocking I/O

Node.js uses non-blocking I/O operations, allowing the application to handle multiple requests simultaneously:

const fs = require('fs');

// Non-blocking file read
fs.readFile('large-file.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error:', err);
return;
}
console.log('File read complete');
});

// This will execute immediately, not waiting for file read
console.log('This executes while file is being read');

How Node.js Works

Single-Threaded Event Loop

Node.js uses a single-threaded event loop model:

  1. Main Thread: Executes JavaScript code
  2. Event Queue: Stores callbacks and events
  3. Event Loop: Processes events from the queue
  4. Worker Threads: Handle I/O operations in the background
// Single-threaded execution example
console.log('1. Start');

setTimeout(() => {
console.log('2. Timeout callback');
}, 0);

setImmediate(() => {
console.log('3. Immediate callback');
});

process.nextTick(() => {
console.log('4. Next tick callback');
});

console.log('5. End');

// Execution order:
// 1. Start
// 5. End
// 4. Next tick callback
// 2. Timeout callback
// 3. Immediate callback

Asynchronous Programming Model

Node.js excels at asynchronous programming:

// Asynchronous HTTP request
const https = require('https');

function fetchData(url) {
return new Promise((resolve, reject) => {
https.get(url, (response) => {
let data = '';

response.on('data', (chunk) => {
data += chunk;
});

response.on('end', () => {
resolve(JSON.parse(data));
});
}).on('error', reject);
});
}

// Usage
fetchData('https://api.github.com/users/octocat')
.then(data => console.log(data.name))
.catch(error => console.error('Error:', error));

Node.js Features

1. Cross-Platform

Node.js runs on multiple operating systems:

// Platform detection
console.log('Platform:', process.platform);
console.log('Architecture:', process.arch);
console.log('Node.js version:', process.version);

// Platform-specific code
if (process.platform === 'win32') {
console.log('Running on Windows');
} else if (process.platform === 'darwin') {
console.log('Running on macOS');
} else if (process.platform === 'linux') {
console.log('Running on Linux');
}

2. Rich Module System

Node.js has a comprehensive module system:

// Built-in modules
const fs = require('fs');
const http = require('http');
const path = require('path');
const crypto = require('crypto');

// Custom modules
const myModule = require('./my-module');

// ES6 modules (Node.js 12+)
import express from 'express';
import { readFile } from 'fs/promises';

3. NPM Ecosystem

Access to millions of packages through NPM:

# Install packages
npm install express
npm install lodash
npm install moment

# Package.json example
{
"dependencies": {
"express": "^4.18.2",
"lodash": "^4.17.21"
}
}

4. Real-time Applications

Perfect for real-time applications:

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
console.log('Client connected');

ws.on('message', (message) => {
console.log('Received:', message);

// Broadcast to all clients
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});

ws.on('close', () => {
console.log('Client disconnected');
});
});

Node.js vs Other Technologies

Node.js vs PHP

FeatureNode.jsPHP
LanguageJavaScriptPHP
ExecutionAsynchronousSynchronous
PerformanceHigh for I/O operationsGood for web development
Learning CurveEasy (if you know JS)Moderate
EcosystemNPM (1M+ packages)Composer (300K+ packages)

Node.js vs Python

FeatureNode.jsPython
LanguageJavaScriptPython
PerformanceFast for I/OGood for CPU-intensive
SyntaxC-styleIndentation-based
LibrariesNPMPyPI
Use CasesWeb APIs, Real-timeData Science, AI

Node.js vs Java

FeatureNode.jsJava
LanguageJavaScriptJava
ExecutionInterpretedCompiled
Memory UsageLowerHigher
Startup TimeFastSlower
EnterpriseGrowingEstablished

Advantages of Node.js

1. Single Language Development

// Frontend (Browser)
const user = { name: 'John', age: 30 };
localStorage.setItem('user', JSON.stringify(user));

// Backend (Node.js)
const user = JSON.parse(localStorage.getItem('user'));
console.log(user.name); // John

2. High Performance

// Efficient I/O operations
const fs = require('fs').promises;

async function processFiles() {
const files = await fs.readdir('./data');

// Process files concurrently
const promises = files.map(async (file) => {
const content = await fs.readFile(`./data/${file}`, 'utf8');
return processContent(content);
});

const results = await Promise.all(promises);
return results;
}

3. Scalability

// Cluster module for scaling
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
// Fork workers
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}

cluster.on('exit', (worker) => {
console.log(`Worker ${worker.process.pid} died`);
cluster.fork();
});
} else {
// Worker process
require('./app.js');
}

4. Rich Ecosystem

// Popular Node.js packages
const express = require('express'); // Web framework
const mongoose = require('mongoose'); // MongoDB ODM
const socket.io = require('socket.io'); // Real-time communication
const passport = require('passport'); // Authentication
const bcrypt = require('bcrypt'); // Password hashing
const jwt = require('jsonwebtoken'); // JWT tokens

Common Use Cases

1. Web Applications

const express = require('express');
const app = express();

app.get('/', (req, res) => {
res.send('Hello World!');
});

app.listen(3000, () => {
console.log('Server running on port 3000');
});

2. APIs and Microservices

// REST API
app.get('/api/users', (req, res) => {
res.json({ users: ['John', 'Jane', 'Bob'] });
});

app.post('/api/users', (req, res) => {
const { name, email } = req.body;
// Create user logic
res.json({ message: 'User created', user: { name, email } });
});

3. Real-time Applications

// Chat application
const io = require('socket.io')(server);

io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
});

4. Command Line Tools

#!/usr/bin/env node

const { program } = require('commander');

program
.version('1.0.0')
.description('My CLI tool')
.option('-d, --debug', 'output extra debugging')
.option('-s, --small', 'small pizza size')
.option('-p, --pizza-type <type>', 'flavour of pizza');

program.parse(process.argv);

const options = program.opts();
console.log('Options:', options);

Getting Started

Installation

# Download from nodejs.org
# Or use package managers

# macOS with Homebrew
brew install node

# Ubuntu/Debian
sudo apt install nodejs npm

# Windows
# Download installer from nodejs.org

First Application

// hello.js
console.log('Hello, Node.js!');
console.log('Node.js version:', process.version);
console.log('Platform:', process.platform);
node hello.js

Next Steps

Now that you understand the basics of Node.js, continue with:

  1. Node.js - Environment Setup - Install and configure Node.js
  2. Node.js - First Application - Build your first application
  3. Node.js - REPL Terminal - Learn the interactive shell
  4. Node.js - Package Manager (NPM) - Master package management

Node.js Introduction Complete! You now understand what Node.js is, how it works, and why it's popular. Ready to start building applications?