Skip to main content

Command Palette

Search for a command to run...

Node.js Basics: A Beginner’s Guide to Server-Side JavaScript

Learn Node.js Setup, Architecture, Modules, and Asynchronous Programming

Published
4 min read
Node.js Basics: A Beginner’s Guide to Server-Side JavaScript
M

I'm Mohammed Shakeel, an aspiring Android developer and software engineer with a keen interest in web development. I am passionate about creating innovative mobile applications and web solutions that are both functional and aesthetically pleasing.

Node.js has revolutionized the way developers create scalable, server-side applications. By enabling JavaScript to run outside the browser, Node.js provides a lightweight and efficient environment perfect for building fast and scalable web applications. This blog will guide you through the basics of Node.js, from installation to creating a server and understanding its asynchronous programming model.


What is Node.js?

Node.js is a runtime environment that allows developers to execute JavaScript code outside of a web browser. It’s built on Google Chrome's V8 engine, offering high performance and non-blocking I/O operations, making it ideal for real-time applications like chat systems, streaming services, and REST APIs.


Installing and Setting Up Node.js

Installation:

  1. Download Node.js from the official website.

  2. Select the LTS version for stability.

  3. Follow the installer instructions to complete the setup.

Verifying Installation:

After installation, verify the version of Node.js and npm (Node Package Manager):

node -v
npm -v

Understanding the Node.js Architecture and Event Loop

Key Components:

  1. Single-Threaded Model: Node.js uses a single thread to handle multiple client requests.

  2. Event Loop: At its core, Node.js relies on an event-driven, non-blocking architecture to manage asynchronous tasks.

How the Event Loop Works:

The event loop is a mechanism that continuously checks for pending tasks, executes them, and delegates I/O operations to the thread pool.
Example:

console.log("Start");

setTimeout(() => {
  console.log("Asynchronous operation");
}, 1000);

console.log("End");

Output:

Start
End
Asynchronous operation

The event loop ensures non-blocking execution, allowing other tasks to run while waiting for the timeout.


Basic Node.js Modules

1. File System (fs):

Used for file operations like reading, writing, and updating files.
Example: Reading a file asynchronously

const fs = require('fs');

fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(data);
});

2. Path:

Handles file and directory paths.
Example: Joining paths

const path = require('path');

const filePath = path.join(__dirname, 'example.txt');
console.log(filePath);

3. OS:

Provides information about the operating system.
Example: Fetching OS details

const os = require('os');

console.log("Platform:", os.platform());
console.log("Free Memory:", os.freemem());

4. HTTP:

Used to create web servers.
Example: Setting up a basic HTTP server

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello, Node.js!');
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

Package Management with npm

What is npm?

npm (Node Package Manager) is a tool for managing packages and dependencies in Node.js projects.

Common Commands:

  1. Initialize a project:

     npm init
    

    This creates a package.json file for managing dependencies and metadata.

  2. Install a package:

     npm install express
    
  3. Install a package globally:

     npm install -g nodemon
    
  4. Install dependencies from package.json:

     npm install
    

Creating a Basic Server

Setting Up an HTTP Server:

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end('<h1>Welcome to Node.js</h1>');
  } else if (req.url === '/about') {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end('<h1>About Page</h1>');
  } else {
    res.writeHead(404, { 'Content-Type': 'text/html' });
    res.end('<h1>404 Not Found</h1>');
  }
});

server.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

Understanding Routing and Requests:

  • Routing: Define responses for different URLs.

  • Handling Requests: Use the req object to access client requests.


Understanding Callbacks in Node.js

What are Callbacks?

Callbacks are functions passed as arguments to other functions, executed after an operation completes.

Example:

function fetchData(callback) {
  setTimeout(() => {
    callback("Data fetched!");
  }, 1000);
}

fetchData((data) => {
  console.log(data);
});

Handling Errors in Callbacks:

fs.readFile('nonexistent.txt', 'utf8', (err, data) => {
  if (err) {
    console.error("Error reading file:", err);
    return;
  }
  console.log(data);
});

Event-Driven Programming in Node.js

The Event Emitter Model:

The events module allows us to create and handle custom events.

Creating Custom Events:

const EventEmitter = require('events');
const eventEmitter = new EventEmitter();

// Define an event
eventEmitter.on('greet', (name) => {
  console.log(`Hello, ${name}!`);
});

// Trigger the event
eventEmitter.emit('greet', 'Alice');

Real-World Example:

Server emits an event when a request is received:

const http = require('http');
const EventEmitter = require('events');

const serverEmitter = new EventEmitter();

serverEmitter.on('requestReceived', () => {
  console.log('Request received!');
});

const server = http.createServer((req, res) => {
  serverEmitter.emit('requestReceived');
  res.end('Hello!');
});

server.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

Conclusion

Node.js simplifies server-side development with its efficient, non-blocking I/O model and event-driven architecture. By mastering its basics—like setting up servers, managing packages, and working with modules—you can unlock its potential for creating scalable and high-performance applications. Whether you're building a simple REST API or a complex real-time app, Node.js is an indispensable tool for modern web development.