MCPcopy
hub / github.com/learning-zone/nodejs-basics

github.com/learning-zone/nodejs-basics @main sqlite

repository ↗ · DeepWiki ↗
12 symbols 18 edges 56 files 0 documented · 0%
README

Node.js Basics

Click ★ if you like the project. Your contributions are heartily ♡ welcome.

Related Topics

Table of Contents

# 1. INTRODUCTION

Q. What is Node.js?

Node.js is an open-source server side runtime environment built on Chrome\'s V8 JavaScript engine. It provides an event driven, non-blocking (asynchronous) I/O and cross-platform runtime environment for building highly scalable server-side applications using JavaScript.

<b><a href="#table-of-contents">↥ back to top</a></b>

Q. What is Node.js Process Model?

The Node.js Process Model is a single-threaded, event-driven architecture designed to handle many concurrent client requests efficiently. Unlike traditional web servers that create a new thread for every request, Node.js uses a Single-Threaded Event Loop to manage all non-blocking operations

Features:

  • Runs in a single process with a single thread, requiring fewer resources than multi-threaded platforms
  • All incoming requests are handled by that one thread
  • Blocking I/O (file system, database, network) is handed off asynchronously — the thread doesn\'t wait for it to complete
  • When async work finishes, a callback is queued and executed, and the response is sent back to the client

Flow:

  1. Client requests arrive and are placed in the Event Queue
  2. The Event Loop picks them up one by one
  3. If a request needs blocking I/O → it\'s assigned to a thread pool (libuv) in the background
  4. The main thread moves on to the next request immediately
  5. When the I/O completes, the callback fires and the response is returned

This is why Node.js is highly scalable for I/O-bound workloads — it never blocks waiting, unlike traditional thread-per-request servers.

<b><a href="#table-of-contents">↥ back to top</a></b>

Q. What are the key features of Node.js?

  • Asynchronous and Event driven – All APIs of Node.js are asynchronous. This feature means that if a Node receives a request for some Input/Output operation, it will execute that operation in the background and continue with the processing of other requests. Thus it will not wait for the response from the previous requests.

  • Fast in Code execution – Node.js uses the V8 JavaScript Runtime engine, the one which is used by Google Chrome. Node has a wrapper over the JavaScript engine which makes the runtime engine much faster and hence processing of requests within Node.js also become faster.

  • Single Threaded but Highly Scalable – Node.js uses a single thread model for event looping. The response from these events may or may not reach the server immediately. However, this does not block other operations. Thus making Node.js highly scalable. Traditional servers create limited threads to handle requests while Node.js creates a single thread that provides service to much larger numbers of such requests.

  • Node.js library uses JavaScript – This is another important aspect of Node.js from the developer\'s point of view. The majority of developers are already well-versed in JavaScript. Hence, development in Node.js becomes easier for a developer who knows JavaScript.

  • There is an Active and vibrant community for the Node.js framework – The active community always keeps the framework updated with the latest trends in the web development.

  • No Buffering – Node.js applications never buffer any data. They simply output the data in chunks.

    ↥ back to top

Q. How does Node.js work?

Node.js is completely event-driven and processes everything on a single thread using a non-blocking I/O model.

Node.js works asynchronously by using the event loop and callback functions, to handle multiple requests coming in parallel. An Event Loop is a functionality which handles and processes all your external events and just converts them to a callback function. It invokes all the event handlers at a proper time. Thus, lots of work is done on the back-end, while processing a single request, so that the new incoming request doesn\'t have to wait if the processing is not complete.

While processing a request, Node.js attaches a callback function to it and moves it to the back-end. Now, whenever its response is ready, an event is called which triggers the associated callback function to send this response.

Core Components:

Component Role
V8 Engine Executes JavaScript on the server (same engine as Chrome)
libuv C library that handles async I/O, thread pool, event loop
Event Queue Holds incoming requests/events in FIFO order
Event Loop Continuously polls the queue and dispatches callbacks
Thread Pool Background workers (libuv) for blocking operations (file, DNS, crypto)

Request Lifecycle:

  1. A request arrives → placed in the Event Queue
  2. The Event Loop picks it up (call stack must be empty)
  3. No blocking I/O? → Process immediately, send response
  4. Blocking I/O needed? → Offload to a thread pool worker, register a callback, free the main thread
  5. Worker completes → fires an event → callback executes → response sent

Key Design Principles:

  • Single-threaded JS execution — no thread management overhead
  • Non-blocking by default — APIs are async with callbacks/promises
  • Observer pattern — events trigger registered listeners
  • Concurrency without threads — achieved via the event loop + callbacks, not parallel execution

What it's great at: High-concurrency I/O-bound workloads (APIs, real-time apps, microservices)

What it's not ideal for: CPU-intensive tasks (use worker_threads or child_process for those)

<b><a href="#table-of-contents">↥ back to top</a></b>

Q. What is difference between process and threads in Node.js?

In Node.js, the main difference between a process (using the child_process or cluster modules) and a thread (using the worker_threads module) lies in how they handle memory and isolation.

Process

A process is an independent program instance with its own memory space. - Created via child_process.fork() — spawns a new V8 instance - Isolated memory — no sharing between processes - Communicates via IPC (message passing) - If it crashes, only that process is affected - Higher creation overhead

Thread

A thread is a unit of execution within a process. - Created via worker_threads module - Shared memory within the same process (via SharedArrayBuffer) - Communicates via postMessage or shared memory - A crash can affect the entire process - Lower creation overhead

Comparison Table

Process Thread
Memory Isolated Shared within process
Creation cost Higher (new V8 instance) Lower
Communication IPC (message passing) SharedArrayBuffer / postMessage
Crash impact Only that process Can crash entire process
Use case Separate Node.js apps, external commands CPU-intensive JS tasks

When to use which?

  • Use child_process.fork() — when you need full isolation (separate scripts, different environments)
  • Use worker_threads — for CPU-heavy JS tasks (image processing, parsing, crypto) where you want low overhead and optional memory sharing

Node.js\'s main event loop always runs on a single thread — neither approach blocks it when used correctly.

<b><a href="#table-of-contents">↥ back to top</a></b>

# 2. NODE.JS ARCHITECTURE

Q. How does Node.js works?

Node.js is single-threaded and event-driven, using a non-blocking I/O model to handle many concurrent operations efficiently.

Node Architecture

Core Components

Component Role
V8 Engine Executes JavaScript (same engine as Chrome)
libuv C library handling async I/O, thread pool, and event loop
Event Queue Holds incoming requests/events in FIFO order
Event Loop Continuously polls the queue and dispatches callbacks
Thread Pool Background workers for blocking operations (file, DNS, crypto)

Request Lifecycle

  1. Request arrives → placed in the Event Queue
  2. Event Loop picks it up (only when the call stack is empty)
  3. No blocking I/O? → Process immediately, send response
  4. Blocking I/O needed? → Offload to a thread pool worker, register a callback, free the main thread
  5. Worker completes → fires an event → callback executes → response sent
Client Requests
      ↓
  Event Queue
      ↓
  Event Loop (single thread)
    ├── Non-blocking? → Process & respond immediately
    └── Blocking I/O? → Thread Pool (libuv)
                              ↓
                         Callback fired → response sent

Key Design Principles

  • Single-threaded JS execution — no thread management overhead
  • Non-blocking by default — APIs are async with callbacks/promises
  • Observer pattern — events trigger registered listeners
  • Concurrency without threads — achieved via event loop + callbacks, not parallel execution

    ↥ back to top

Q. What are the core modules of Node.js?

Node.js has a set of core modules that are part of the platform and come with the Node.js installation. These modules can be loaded into the program by using the require function.

The following table lists some of the important core modules in Node.js.

Name Description
assert It is used by Node.js for testing itself.
buffer Handle raw binary data outside the V8 heap
child_process Spawn child processes (exec, spawn, fork)
cluster This module is used by Node.js to take advantage of multi-core systems, so that it can handle more load.
console It is used to write data to console. Node.js has a Console object which contains functions to write data to console.
crypto Cryptographic functions — hashing, encryption, HMAC
http/https Create HTTP/HTTPS servers and make requests
url It includes methods for URL resolution and parsing.
querystring It includes methods to deal with query string.
path Utilities for working with file and directory paths
fs File system — read, write, update, delete, rename files.
stream Readable, Writable, Duplex, and Transform streams
worker_threads Run CPU-intensive JS in background threads
util It includes utility functions useful for programmers.
zlib It is used to compress and decompress data.

Example:

const http   = require('http');
const fs     = require('fs');
const path   = require('path');
const crypto = require('crypto');

// HTTP server
http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello World');
}).listen(3000);

// File path
const filePath = path.join(__dirname, 'data', 'file.txt');

// Read file
fs.readFile(filePath, 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

// Hash a string
const hash = crypto.createHash('sha256').update('secret').digest('hex');
console.log(hash);
<b><a href="#table-of-contents">↥ back to top</a></b>

Q. What do you understand by Reactor Pattern in Node.js?

Reactor Pattern is used to avoid the blocking of the Input/Output operations. It provides us with a handler that

Core symbols most depended-on inside this repo

connected
called by 3
nodejs-basics/tls.js
generateAccessToken
called by 2
jwt-asymmetric-cryptography-authentication/authServer.js
ask
called by 2
nodejs-basics/standard-input-output.js
add
called by 2
nodejs-basics/assert.js
generateAccessToken
called by 2
jwt-authentication/authServer.js
recursive
called by 1
nodejs-basics/timmer.js
authenticateToken
called by 0
jwt-asymmetric-cryptography-authentication/server.js
initial
called by 0
node-jwt-mysql-auth/server.js

Shape

Function 10
Class 2

Languages

TypeScript100%

Modules by API surface

nodejs-basics/timmer.js2 symbols
nodejs-basics/event.js2 symbols
nodejs-basics/tls.js1 symbols
nodejs-basics/standard-input-output.js1 symbols
nodejs-basics/assert.js1 symbols
node-jwt-mysql-auth/server.js1 symbols
jwt-authentication/server.js1 symbols
jwt-authentication/authServer.js1 symbols
jwt-asymmetric-cryptography-authentication/server.js1 symbols
jwt-asymmetric-cryptography-authentication/authServer.js1 symbols

Dependencies from manifests, versioned

bcryptjs2.4.3 · 1×
body-parser1.19.0 · 1×
cors2.8.5 · 1×
dotenv8.6.0 · 1×
express4.17.1 · 1×
jsonwebtoken8.5.1 · 1×
mysql22.1.0 · 1×
node-rest-client3.1.0 · 1×
nodemon2.0.20 · 1×
sequelize5.21.3 · 1×

Datastores touched

mydbDatabase · 1 repos

For agents

$ claude mcp add nodejs-basics \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact