What is Node.js

1. Definition

Node.js is a runtime environment that allows you to run JavaScript outside the browser. It is mainly used to build backend applications like servers and APIs.

2. When to Use Node.js

  • Building backend/server-side applications
  • Creating REST APIs
  • Real-time apps (chat, live updates)
  • Full-stack development (MERN)

3. Where it is Used

  • Web servers
  • APIs
  • Real-time systems
  • Microservices
  • CLI tools

4. Why Use Node.js

  • JavaScript for both frontend & backend
  • Fast (non-blocking)
  • Handles multiple requests
  • Huge npm ecosystem

5. How Node.js Works

  • Built on Chrome V8 JavaScript Engine
  • Uses single-threaded event loop
  • Handles requests asynchronously
  • Non-blocking I/O operations

Basic Syntax

const http = require("http");

const server = http.createServer((req, res) => {
  res.write("Hello from Node.js");
  res.end();
});

server.listen(3000);

Real Example

const http = require("http");

const server = http.createServer((req, res) => {
  if (req.url === "/api/user") {
    res.write(JSON.stringify({ name: "Manaswini", role: "Developer" }));
  } else {
    res.write("Home Page");
  }
  res.end();
});

server.listen(3000);

7. Advantages

  • Fast and scalable
  • Non-blocking architecture
  • JavaScript everywhere
  • Huge npm ecosystem

8. Disadvantages

  • Not suitable for CPU-heavy tasks
  • Callback complexity (callback hell)
  • Single-thread limitations

Interview Points

  • Node.js is a runtime
  • Single-threaded event loop
  • Non-blocking I/O
  • Best for I/O-heavy apps