0% found this document useful (0 votes)
2 views5 pages

Nodejs Complete Basics

This document provides a comprehensive guide on setting up a Node.js project, including initializing with npm, creating a basic HTTP server, serving static files, and performing file operations. It covers handling different content types, processing POST requests, data sanitization, and using EventEmitter and Server-Sent Events (SSE). Best practices for modern Node.js development are also highlighted, such as using ES modules and ensuring proper error handling.

Uploaded by

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

Nodejs Complete Basics

This document provides a comprehensive guide on setting up a Node.js project, including initializing with npm, creating a basic HTTP server, serving static files, and performing file operations. It covers handling different content types, processing POST requests, data sanitization, and using EventEmitter and Server-Sent Events (SSE). Best practices for modern Node.js development are also highlighted, such as using ES modules and ensuring proper error handling.

Uploaded by

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

1.

Initialize a Project
Every [Link] project starts with npm init (npm = Node Package Manager).
npm init -y

This creates a [Link] file.


ES Module Setup:
{
"type": "module"
}

■ Tip: Using "type": "module" lets you use modern import/export syntax instead of require/[Link].
// With "type": "module"
import fs from "node:fs";

// Without (CommonJS style)


const fs = require("fs");

2. Basic HTTP Server


import http from "node:http";

const PORT = 3000;


const content = "<h1>Hello [Link]</h1>";

const server = [Link]((req, res) => {


[Link] = 200;
[Link]("Content-Type", "text/html");
[Link](content);
});

[Link](PORT, () =>
[Link](`■ Server running at [Link]
);

Alternative header syntax:


[Link](200, { "Content-Type": "text/html" });

■ Always set the Content-Type header so the browser knows how to handle your response (HTML, JSON, CSS, etc.).

3. Serving Static Files


Steps: Identify request → Build path → Read file → Send response
import http from "node:http";
import path from "node:path";
import { readFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";

const __filename = fileURLToPath([Link]);


const __dirname = [Link](__filename);

const server = [Link](async (req, res) => {


const requestedResource = [Link];
const filePath = [Link](
__dirname,
"public",
requestedResource === "/" ? "[Link]" : requestedResource
);

try {
const content = await readFile(filePath, "utf8");
[Link](200, { "Content-Type": "text/html" });
[Link](content);
} catch (err) {
[Link](404, { "Content-Type": "text/plain" });
[Link]("File not found");
}
});

[Link](3000, () => [Link]("■ Server running on port 3000"));

■ Place static files (HTML, CSS, JS, images) in a public/ folder.

4. Working with Paths


import path from "node:path";
import { readFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";

const __filename = fileURLToPath([Link]);


const __dirname = [Link](__filename);

const pathToResource = [Link](__dirname, "public", "[Link]");


const content = await readFile(pathToResource, "utf8");

[Link](content);

[Link]("CWD:", [Link]());

■ Use [Link]() for paths relative to where you run the app. Use __dirname for paths relative to the script file.

5. File System (FS)


Operations: Read, Create, Update, Delete, Rename
import { readFile, writeFile, appendFile, unlink, rename } from "node:fs/promises";

const filePath = "./[Link]";

async function fileOps() {


try {
await writeFile(filePath, "Hello [Link]\n");
[Link]("■ File created");

const content = await readFile(filePath, "utf8");


[Link]("■ File content:", content);

await appendFile(filePath, "This is an update.\n");


[Link]("✏■ File updated");

await rename(filePath, "./[Link]");


[Link]("■ File renamed");

await unlink("./[Link]");
[Link]("■■ File deleted");
} catch (err) {
[Link]("■ Error:", err);
}
}
fileOps();

Callbacks vs Promises vs Async/Await


// 1. Callback
import fs from "node:fs";
[Link]("[Link]", "utf8", (err, data) => {
if (err) [Link]("■ Callback Error:", err);
else [Link]("■ Callback read:", data);
});

// 2. Promises
import { readFile } from "node:fs/promises";
readFile("[Link]", "utf8")
.then((data) => [Link]("■ Promise read:", data))
.catch((err) => [Link]("■ Promise Error:", err));

// 3. Async/Await
import { readFile } from "node:fs/promises";
async function readMyFile() {
try {
const data = await readFile("[Link]", "utf8");
[Link]("■ Async/Await read:", data);
} catch (err) {
[Link]("■ Async/Await Error:", err);
}
}
readMyFile();

■ Prefer async/await for readability.

6. Content Type Handling


function getContentType(ext) {
const types = {
".js": "text/javascript",
".css": "text/css",
".json": "application/json",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".svg": "image/svg+xml",
};
return types[[Link]()] || "text/html";
}

[Link](getContentType(".css")); // text/css

7. Handling POST Requests


import http from "node:http";

const server = [Link](async (req, res) => {


if ([Link] === "/submit" && [Link] === "POST") {
let body = "";
for await (const chunk of req) body += chunk;

try {
const data = [Link](body);
[Link](201, { "Content-Type": "application/json" });
[Link]([Link](data));
} catch (err) {
[Link] = 400;
[Link]("Invalid JSON");
}
}
});

8. Data Sanitization
Install: npm install sanitize-html
import sanitizeHtml from "sanitize-html";

const dirty = '<script>alert("hack")</script>';


const clean = sanitizeHtml(dirty);
[Link]("Clean:", clean);

const sanitizedData = {};


for (const [key, value] of [Link](data)) {
sanitizedData[key] =
typeof value === "string"
? sanitizeHtml(value, { allowedTags: ["b"], allowedAttributes: {} })
: value;
}

9. EventEmitter
import { EventEmitter } from "node:events";

const emitter = new EventEmitter();

[Link]("greet", (name) => [Link](`Hello ${name}! ■`));


[Link]("greet", "Ali");

■ EventEmitter is widely used internally in [Link] (e.g., streams, HTTP).

10. Server-Sent Events (SSE)


import http from "node:http";

const server = [Link]((req, res) => {


if ([Link] === "/events") {
[Link](200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
});

[Link]("data: Connected to server\n\n");


[Link]("close", () => [Link]());
} else {
[Link](404, { "Content-Type": "text/plain" });
[Link]("Not Found");
}
});

[Link](3000, () => [Link]("■ SSE server started on port 3000"));


const es = new EventSource("[Link]
const list = [Link]("events");

[Link] = (event) => {


const li = [Link]("li");
[Link] = [Link];
[Link](li);
};

[Link] = () => {
const li = [Link]("li");
[Link] = "■■ Connection lost";
[Link](li);
};

[Link]("beforeunload", () => [Link]());

■ Best Practices
• Use ES modules (import/export) in modern [Link] projects.
• Always handle errors in async operations.
• Sanitize user input to prevent XSS attacks.
• Use .writeHead() for multiple headers in one step.
• Use [Link]() and [Link] for cross-platform paths.
• Prefer async/await for cleaner async code.

You might also like