[go: up one dir, main page]

0% found this document useful (0 votes)
19 views11 pages

Node.js Server-Side JavaScript Guide

Node.js is a server-side runtime environment for JavaScript, built on Google's V8 engine, enabling developers to use JavaScript for both front-end and back-end development. The document covers its evolution, internal architecture, asynchronous programming patterns, and ecosystem including npm, Express.js, and database integration with ORM tools like Prisma. It also discusses best practices for testing, scaling, deployment, and security in modern Node.js applications.

Uploaded by

Sofija Milovic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views11 pages

Node.js Server-Side JavaScript Guide

Node.js is a server-side runtime environment for JavaScript, built on Google's V8 engine, enabling developers to use JavaScript for both front-end and back-end development. The document covers its evolution, internal architecture, asynchronous programming patterns, and ecosystem including npm, Express.js, and database integration with ORM tools like Prisma. It also discusses best practices for testing, scaling, deployment, and security in modern Node.js applications.

Uploaded by

Sofija Milovic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Node.

js: The Definitive Guide to Server-Side JavaScript

Version: 2026.1

Subject: Software Architecture & Web Development

Page 1: Introduction and History

[Link] is not a programming language, nor is it a framework. It is a runtime environment that


allows JavaScript to be executed on the server side. Built on Google’s V8 JavaScript engine, it
changed the landscape of web development by enabling "JavaScript Everywhere"—the use of a
single language for both front-end and back-end development.

The Evolution of [Link]

 2009: Ryan Dahl introduces [Link] at JSConf EU.

 2010: [Link] is released, becoming the standard web framework.

 2015: The [Link] Foundation is formed, merging [Link] and [Link].

 2020s: Introduction of native ESM (ECMAScript Modules) support and improved security
features.

 2026: Native TypeScript execution and built-in test runners become standard features.

Page 2: Internal Architecture

The power of [Link] lies in its "Engine Room." It consists of three main layers: the JavaScript
Library, the C++ Binding, and the Core Engines.

The V8 Engine

Written in C++, V8 is responsible for taking JavaScript code and compiling it into machine code.
It uses an optimization technique called Just-In-Time (JIT) Compilation, which analyzes code
during execution and optimizes frequently used paths.

Libuv: The Magic of Asynchrony

Libuv is a C library that handles the "Event Loop" and the "Thread Pool." While JavaScript is
single-threaded, Libuv allows Node to offload tasks like file system operations and network
requests to the operating system or a background pool of threads.
Page 3: The Event Loop Deep Dive

The Event Loop is what allows [Link] to perform non-blocking I/O. It works in a continuous
cycle, checking for completed tasks and executing their callbacks.

The Six Phases of the Loop

1. Timers: Processes setTimeout and setInterval.

2. Pending Callbacks: Handles I/O errors that were delayed.

3. Idle, Prepare: Used only internally by the system.

4. Poll: The most critical phase; it retrieves new I/O events.

5. Check: Executes setImmediate() callbacks.

6. Close Callbacks: Handles the destruction of sockets or handles.

Page 4: Asynchronous Programming Patterns

To manage the non-blocking nature of [Link], developers use several patterns to handle data
that isn't available immediately.

 Callbacks: The original method, often leading to "Callback Hell" (nested structures).

 Promises: Introduced in ES6 to provide a cleaner way to handle success or failure of


async tasks.

 Async/Await: The modern standard, making asynchronous code look and behave like
synchronous code.

JavaScript

// Example of modern Async/Await

async function fetchData() {

try {

const data = await [Link]('SELECT * FROM users');

[Link](data);

} catch (err) {
[Link](err);

Page 5: Node Package Manager (npm)

npm is the backbone of the [Link] ecosystem. It allows developers to share and reuse code via
"packages."

Key Files

 [Link]: Contains metadata about the project and the list of dependencies.

 [Link]: Ensures that every developer on a team installs the exact same
version of every dependency, preventing "it works on my machine" errors.

 node_modules: The folder where all downloaded code lives.

Page 6: Core Modules and the File System

[Link] comes with built-in modules so you don't have to reinvent the wheel.

 FS (File System) Module: Allows you to interact with the computer's storage.

 Path Module: Essential for building file paths that work on both Windows (backslashes)
and Linux/macOS (forward slashes).

 OS Module: Provides information about the host computer's RAM, CPU, and network
interfaces.

Page 7: Building Web Servers with Express

While [Link] has a built-in http module, [Link] is the most popular way to build web APIs.

Middleware Concept

Middleware functions are functions that have access to the request object (req), the response
object (res), and the next function in the application’s request-response cycle. This allows for
features like logging, authentication, and data parsing to be added easily.
Page 8: Streams and Buffers

One of the most efficient features of [Link] is its ability to handle large amounts of data using
Streams. Instead of reading a 4GB file into memory (which would crash the server), [Link]
reads it piece by piece (chunks).

 Readable Streams: Reading data (e.g., reading a file).

 Writable Streams: Writing data (e.g., writing to a file).

 Duplex/Transform: Streams that can both read and write or modify data as it passes
through.

Page 9: Database Connectivity

[Link] is "database agnostic," meaning it can work with anything.

 NoSQL (MongoDB): Uses a JSON-like format (BSON), which feels natural to JavaScript
developers.

 SQL (PostgreSQL): Used for relational data. Developers typically use Prisma or Sequelize
as ORMs (Object-Relational Mappers) to write database queries using JavaScript objects
instead of raw SQL strings.

Page 10: Testing and Debugging

Quality code requires testing. By 2026, [Link] has a built-in test runner, but many still use:

 Vitest: A blazing fast unit test runner.

 Supertest: Specifically for testing HTTP endpoints.

 Debugging: Developers use the Chrome DevTools or the built-in VS Code debugger to set
breakpoints and inspect the "call stack" in real-time.

Page 11: Scaling and Performance

[Link] can scale in two ways:

1. Vertical Scaling: Increasing the power of the server (more RAM/CPU).

2. Horizontal Scaling: Running multiple instances of the application.


The Cluster Module

Since [Link] is single-threaded, it only uses one CPU core. The Cluster Module allows you to
"fork" multiple processes to utilize every core available on the server, effectively multiplying the
performance.

Page 12: Deployment and Security

The final step is moving code from a laptop to the "Cloud."

Best Practices for 2026

 Docker: Wrapping the app in a "container" so it runs the same way on any server.

 Environment Variables: Storing API keys in .env files rather than in the code.

 PM2: A process manager that ensures your [Link] app automatically restarts if it ever
crashes.

 CI/CD: Using GitHub Actions to automatically run tests and deploy whenever code is
updated.

 Page 2: Internal Architecture (Expanded)


 To understand how [Link] handles thousands of connections on a single
thread, we look at the interaction between the V8 engine and the Libuv thread
pool.
 How it works in practice:
 When you make a request to read a file, [Link] doesn't wait. It sends the
request to Libuv, which handles the operation in the background. Once the file is
ready, Libuv pushes a callback into the "Task Queue" for the V8 engine to
execute.

 Page 4: Asynchronous Patterns (Code Examples)


 To illustrate the evolution of JavaScript, use these three snippets showing how
we handle a simple database fetch.
 1. The "Callback" Way (Legacy)
 JavaScript
 [Link](1, (err, user) => {
 if (err) return [Link](err);
 [Link]([Link], (err, profile) => {
 [Link](profile);
 });
 });
 2. The "Promise" Way (Modern)
 JavaScript
 [Link](1)
 .then(user => [Link]([Link]))
 .then(profile => [Link](profile))
 .catch(err => [Link](err));
 3. The "Async/Await" Way (Standard in 2026)
 JavaScript
 try {
 const user = await [Link](1);
 const profile = await [Link]([Link]);
 [Link](profile);
 } catch (err) {
 [Link](err);
 }

 Page 7: Building a Web Server ([Link] Example)


 This is a standard "Hello World" boilerplate for a modern API.
 JavaScript
 import express from 'express';
 const app = express();
 const PORT = 3000;

 // Middleware to parse JSON
 [Link]([Link]());

 // A simple GET route
 [Link]('/api/status', (req, res) => {
 [Link](200).json({ status: 'Online', timestamp: new Date() });
 });

 // A POST route to receive data
 [Link]('/api/users', (req, res) => {
 const newUser = [Link];
 // Logic to save user to database would go here
 [Link](201).send(`User ${[Link]} created!`);
 });

 [Link](PORT, () => {
 [Link](`Server running at [Link]
 });

 Page 11: Scaling with the Cluster Module


 This code allows a [Link] app to use all available CPU cores, which is essential
for production performance.
 JavaScript
 import cluster from 'node:cluster';
 import http from 'node:http';
 import { availableParallelism } from 'node:os';

 if ([Link]) {
 const numCPUs = availableParallelism();
 [Link](`Primary ${[Link]} is running. Forking for ${numCPUs} CPUs...`);

 // Fork workers for every CPU core
 for (let i = 0; i < numCPUs; i++) {
 [Link]();
 }
 } else {
 // Workers can share any TCP connection
 [Link]((req, res) => {
 [Link](200);
 [Link]('Hello from the Worker process!\n');
 }).listen(8000);
 }

 Page 12: Security Checklist (Visual Reference)


 In your document, you should include a "Security Hardening" table:

Threat Mitigation Strategy Tool/Library


XSS Attacks Sanitize user input and set Content Security Policy helmet
Brute Force Limit the number of requests from a single IP express-rate-limit
Data Leakage Never log sensitive info or hardcode secrets dotenv
SQL Injection Use parameterized queries or ORMs Prisma / Sequelize

To help you fill out the remaining pages of your 12-page document, I have expanded Page 5
(The Ecosystem) and Page 9 (Databases) into full-scale tutorials. These include detailed
explanations, workflows, and code blocks to ensure your document is both high-quality and
comprehensive.

Page 5: The npm Ecosystem & Dependency Management

The Node Package Manager (npm) is more than just a downloader; it is a sophisticated system
for managing software lifecycles.

The Workflow of a Modern Developer

1. Initialization: Running npm init -y creates your [Link] file. This is the "brain" of
your project.

2. Installation: When you run npm install <package>, npm adds the library to
node_modules and records the exact version in [Link].
3. Scripts: You can automate tasks using the "scripts" section of the JSON file:

JSON

"scripts": {

"start": "node [Link]",

"dev": "nodemon [Link]",

"test": "vitest"

Managing Environments

[Link] differentiates between packages needed for the app to run (dependencies) and
packages needed only for development (devDependencies).

 Production: npm install express

 Development: npm install --save-dev nodemon (Nodemon restarts the server


automatically when you save a file).

Page 9: Database Integration (PostgreSQL & Prisma)

In 2026, raw SQL is rarely written by hand. Instead, developers use Prisma, a Next-Generation
ORM that makes database interactions type-safe.

Step 1: The Schema

In a file named [Link], you define your data model. This acts as the "Single Source of
Truth."

Фрагмент кода

model User {

id Int @id @default(autoincrement())

email String @unique

name String?

posts Post[]

}
model Post {

id Int @id @default(autoincrement())

title String

author User @relation(fields: [authorId], references: [id])

authorId Int

Step 2: Performing Queries

Once the schema is defined, interacting with the database looks like standard JavaScript:

JavaScript

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function main() {

// Create a new user and a post in one transaction

const newUser = await [Link]({

data: {

name: 'Alice',

email: 'alice@[Link]',

posts: {

create: { title: 'Hello World from [Link]' },

},

},

});

[Link](newUser);

}
Page 10: Testing & Quality Assurance (Full Example)

Testing ensures that as your [Link] application grows, new features don't break old ones.

Unit Testing with Vitest

Suppose you have a math utility file. Your test file ([Link]) would look like this:

JavaScript

import { expect, test } from 'vitest';

import { add } from './[Link]';

test('adds 1 + 2 to equal 3', () => {

expect(add(1, 2)).toBe(3);

});

Integration Testing for APIs

Using Supertest, you can simulate real HTTP requests to your Express server without actually
starting it:

JavaScript

import request from 'supertest';

import app from './[Link]';

test('GET /api/status returns 200', async () => {

const response = await request(app).get('/api/status');

expect([Link]).toBe(200);

expect([Link]).toBe('Online');

});

Formatting Tips for your 12-Page Word Doc:


 Font: Use a clean sans-serif font like Arial or Calibri (11pt or 12pt).

 Code Blocks: In Word, put code in a light-gray shaded box or use the Consolas font to
distinguish it from prose.

 Page Breaks: Use Ctrl + Enter to start each major section on a new page to hit that 12-
page mark.

 Images: I have suggested specific locations for diagrams. You can find these by searching
Google Images for the terms in brackets (e.g., "[Link] Event Loop Diagram").

You might also like