Skip to main content

Command Palette

Search for a command to run...

Introduction to Node js

Published
•6 min read•View as Markdown

What is Node.js?

For years, JavaScript was confined to the browser, the language that brought interactivity and dynamic experiences to the client-side of the web.1 Meanwhile, server-side operations were the domain of languages like PHP, Java, Python, and Ruby. These traditional backend languages process requests by creating a new thread for each client, handling databases, business logic, and then sending a response. This model, while robust, can sometimes be resource-intensive, especially under heavy load.

Enter Node.js – a groundbreaking runtime environment that allows you to execute JavaScript code outside of a web browser.2 In simpler terms, Node.js brings the power and familiarity of JavaScript to the server.3 This means developers can now use a single language for both frontend and backend development, streamlining workflows and reducing the cognitive load of switching between different language paradigms.4

Why Node.js is Perfect for Building Fast Web Apps

The true power of Node.js lies in its unique architecture, which sets it apart from traditional server-side languages.5 Node.js operates on a non-blocking, event-driven I/O model.6 This is a fancy way of saying it's incredibly efficient at handling multiple tasks simultaneously without getting bogged down.

Let's use a real-world analogy to understand this better. Imagine you're a busy chef in a restaurant (the server), and customers (clients) are constantly placing orders.

  • Traditional Backend (e.g., PHP/Java): This is like a chef who takes one order, cooks it from start to finish, and only then moves on to the next order. If cooking one dish takes a long time (e.g., waiting for a database query), all other customers have to wait. This is a blocking approach.

  • Node.js: This is like a highly organized chef who takes an order, starts preparing it, and immediately moves on to take the next order while the first dish is simmering.7 When the first dish is ready, a bell rings (an "event"), and the chef quickly attends to it, serves it, and goes back to other tasks. This is a non-blocking, event-driven approach.

Because Node.js doesn't wait for one operation to complete before starting another, it can handle a massive number of concurrent connections with minimal overhead.8 This makes it exceptionally well-suited for:

  • Real-time applications: Think chat applications, live dashboards, and online gaming where instant updates are crucial.9

  • APIs (Application Programming Interfaces): Building fast, scalable APIs that serve data to various clients (web, mobile).10

  • Data streaming: Efficiently handling large files or streams of data.11

  • Single-page applications (SPAs): Providing a fast and responsive backend for modern web applications.12

Node js Architecture

Node.js uses the “Single Threaded Event Loop” architecture to handle multiple concurrent clients. Node.js Processing Model is based on the JavaScript event-based model along with the JavaScript callback mechanism.

How Node.js Handles Multiple Requests with a Single Thread

  • Single main thread runs JavaScript

    • Node.js has one main thread that executes all your application code.

    • This thread does not create a new thread for each request (unlike Java or PHP servers).

  • Event loop + non-blocking I/O

    • When a request comes in, if it needs something slow (like file read, database query, network call), Node.js does not block the main thread.

    • Instead, it hands the job to the OS kernel or libuv’s thread pool.

  • Thread pool as helpers

    • The thread pool has a few worker threads (default 4).

    • These are used for heavy or blocking operations (like file system, crypto, compression).

    • While workers handle those tasks, the main thread continues serving other requests.

  • Callbacks come back via event loop

    • When a worker finishes, the result is pushed into the event loop’s queue.

    • The main thread then picks it up and continues execution.

Setting Up Your First Node.js App Step-by-Step

Getting started with Node.js is straightforward. Here’s how you can set up your environment and create a basic "Hello World" server.

Step 1: Install Node.js

First, you need to install Node.js on your machine. The easiest way is to download the official installer from the Node.js website. Choose the "LTS" (Long Term Support) version, as it's the most stable and recommended for most users.

Once installed, open your terminal or command prompt and verify the installation by typing:

node -v
npm -v

You should see the installed versions of Node.js and npm (Node Package Manager), which is installed alongside Node.js. npm is essential for managing external libraries and packages in your Node.js projects.13

Step 2: Create Your First Node.js Server

Now, let's create a simple HTTP server that responds with "Hello World!".

  1. Create a new directory for your project and navigate into it:

     mkdir my-first-node-app
     cd my-first-node-app
    
  2. Create a new file named app.js (or any other .js filename you prefer) inside this directory.

  3. Open app.js in your favorite text editor and paste the following code:

     const http = require('http'); // Import the built-in http module
    
     const hostname = '127.0.0.1'; // Localhost IP address
     const port = 3000; // Port to listen on
    
     // Create a server instance
     const server = http.createServer((req, res) => {
       // Set the response HTTP header with a status code and content type
       res.statusCode = 200;
       res.setHeader('Content-Type', 'text/plain');
    
       // Send the response body "Hello World"
       res.end('Hello World!\n');
     });
    
     // The server listens on the specified port and hostname
     server.listen(port, hostname, () => {
       console.log(`Server running at http://${hostname}:${port}/`);
     });
    

    Explanation of the code:

    • require('http'): This line imports Node.js's built-in http module, which provides functionality to create HTTP servers and clients.14

    • hostname and port: These define where our server will be accessible.15 127.0.0.1 is localhost, and 3000 is a common port for development.16

    • http.createServer((req, res) => { ... }): This creates an HTTP server. The function passed to createServer is a request listener that executes every time the server receives a request.17

      • req: Represents the incoming request object.18

      • res: Represents the response object that will be sent back to the client.19

    • res.statusCode = 200;: Sets the HTTP status code to 200, indicating success.20

    • res.setHeader('Content-Type', 'text/plain');: Tells the client that the response body is plain text.

    • res.end('Hello World!\n');: Sends "Hello World!" as the response and signals that the response is complete.

    • server.listen(port, hostname, () => { ... });: Starts the server and makes it listen for incoming requests on the specified port and hostname.21 The callback function is executed once the server starts successfully.

  4. Run your server: Go back to your terminal or command prompt, make sure you are in the my-first-node-app directory, and run your script:

     node app.js
    

    You should see the message: Server running at http://127.0.0.1:3000/

  5. Open your web browser and navigate to http://127.0.0.1:3000/. You should see "Hello World!" displayed in your browser.

You've successfully set up and run your first Node.js server! This simple example demonstrates the fundamental principles of Node.js: using JavaScript to create a powerful and efficient backend. From here, you can explore more advanced topics like using popular frameworks like Express.js, connecting to databases, and building complex, scalable web applications.