الـ Streams والـ Backpressure: ملفات أكبر من الـ memory
ليه readFile على ملف كبير بتملا الـ memory، وإزاي الـ streams بتشتغل chunk بـ chunk. الأنواع الأربعة: Readable و Writable و Transform و Duplex. الـ backpressure: write بترجّع false فتستنى drain، و highWaterMark. و for await على readline، و pipeline من stream/promises اللي بيوصّل ويقفل كله صح لو حصل error، و gzip كـ Transform.
نص شرح المعلم والكود الذي كتبه ونتيجة تشغيله، بنفس ترتيب الدرس.
أهلًا بيك. تخيل ملف logs حجمه خمسة جيجا، والـ server عنده جيجا memory بس. لو قريته بـ readFile، Node هيحاول يحطه كله في الـ memory، والـ process هيقع. الحل: الـ streams. بدل ما تشيل الملف كله، بتاخده حتة حتة، كل حتة اسمها chunk، تخلّص منها، وتاخد اللي بعدها. زي ما بتشرب من خرطوم، مش بتشيل الخزان. أول حاجة، نعمل ملف logs كبير، مليون سطر، بـ write stream. وهنا أهم مفهوم في الدرس: الـ backpressure. write بترجّع true لو الـ buffer لسه فيه مكان. ولو رجّعت false، معناها: استنى، أنا مليان، والـ disk مش ملاحق. فبنستنى event اسمه drain، يعني فضيت، وبعدين نكمّل. لو تجاهلت false وفضلت تكتب، كل الكلام بيتكوّم في الـ memory. نشغّل.
import fs from "node:fs";
const mb = (n) => `${Math.round(n / 1024 / 1024)}MB`;
// نكتب ملف logs كبير، سطر سطر، ونحترم الـ backpressure
const out = fs.createWriteStream("access.log");
let waits = 0;
for (let i = 0; i < 1_000_000; i++) {
const line = `${i},GET,/courses/${i % 50},${i % 7 === 0 ? 500 : 200},${(i * 37) % 900}\n`;
if (!out.write(line)) {
waits++;
await new Promise((resolve) => out.once("drain", resolve));
}
}
out.end();
await new Promise((resolve) => out.on("finish", resolve));
console.log("حجم الملف:", mb(fs.statSync("access.log").size));
console.log("مرات الاستنى على drain:", waits > 100 ? "كتير (ده طبيعي)" : waits);المخرجات
$ node main.js حجم الملف: 29MB مرات الاستنى على drain: كتير (ده طبيعي)
ملف حجمه حوالي تلاتين ميجا، والـ write قالت استنى مرات كتير، وكل مرة استنينا drain. ده الطبيعي: الـ CPU أسرع بكتير من الـ disk، والـ backpressure هو اللي بيوازن بينهم. دلوقتي نعدّ الـ errors، يعني السطور اللي فيها five hundred، بالطريقة السهلة: readFileSync، و split، و filter. وبنقيس الـ memory قبل وبعد. نشغّل.
import fs from "node:fs";
const mb = (n) => `${Math.round(n / 1024 / 1024)}MB`;
const before = process.memoryUsage().rss;
const text = fs.readFileSync("access.log", "utf8");
const errors = text.split("\n").filter((l) => l.includes(",500,")).length;
const after = process.memoryUsage().rss;
console.log("errors:", errors);
console.log("الـ memory زادت حوالي:", mb(after - before));المخرجات
$ node main.js errors: 142858 الـ memory زادت حوالي: 123MB
الرقم صح، بس الـ memory زادت أضعاف حجم الملف. لأننا شايلين النص كله، وفوقه array فيها مليون string. نفس الحساب بالـ streams: readline بتقسّم الـ stream لسطور، و for await بتلف عليها واحد واحد. نشغّل.
import fs from "node:fs";
import readline from "node:readline";
const mb = (n) => `${Math.round(n / 1024 / 1024)}MB`;
const before = process.memoryUsage().rss;
const lines = readline.createInterface({
input: fs.createReadStream("access.log"),
crlfDelay: Infinity,
});
let errors = 0;
for await (const line of lines) {
if (line.includes(",500,")) errors++;
}
const after = process.memoryUsage().rss;
console.log("errors:", errors);
console.log("الـ memory زادت حوالي:", mb(Math.max(0, after - before)));المخرجات
$ node main.js errors: 142858 الـ memory زادت حوالي: 23MB
نفس العدد بالزبط، والـ memory زادت حوالي عشرين ميجا بس، بدل مِيّة وعشرين، ومهما الملف كبر، هتفضل قريبة من كده. والسبب إن الـ stream بيقرا chunk بحجم تابت، اسمه highWaterMark، وبشكل افتراضي أربعة وستين كيلو للملفات، وما بيقراش اللي بعده غير لما اللي قبله يتعالج. الاستخدام الاحترافي: pipeline. بتوصّل streams ورا بعض زي المواسير: ملف الـ logs. Transform بيعدّي السطور اللي فيها errors بس. وخد بالك من rest: الـ chunk ممكن يقطع سطر من النص، فبنشيل آخر حتة لحد الـ chunk اللي بعده. gzip بيضغط. وملف بيتكتب. و pipeline بتهتم بالـ backpressure بين كل اتنين لوحدها. نشغّل.
import fs from "node:fs";
import { pipeline } from "node:stream/promises";
import { Transform } from "node:stream";
import zlib from "node:zlib";
const mb = (n) => `${Math.round(n / 1024 / 1024)}MB`;
// Transform: بياخد chunks وبيطلع chunks تانية
let rest = "";
const onlyErrors = new Transform({
transform(chunk, _enc, done) {
const lines = (rest + chunk).split("\n");
rest = lines.pop();
const keep = lines.filter((l) => l.includes(",500,")).join("\n");
done(null, keep ? keep + "\n" : "");
},
});
await pipeline(
fs.createReadStream("access.log"),
onlyErrors,
zlib.createGzip(),
fs.createWriteStream("errors.log.gz"),
);
console.log("errors.log.gz:", mb(fs.statSync("errors.log.gz").size));المخرجات
$ node main.js errors.log.gz: 1MB
ملف مضغوط فيه الـ errors بس، حوالي ميجا واحدة، من ملف تلاتين. وده بالزبط اللي بيحصل لما server بيبعت ملف كبير للمتصفح: الملف Readable، والـ response Writable، و pipeline في النص. ليه pipeline مش pipe العادية؟ لأن pipe لو حصل error في نص السكة، الـ streams التانية بتفضل مفتوحة، والملفات ما بتتقفلش، ودي memory leak. pipeline بتقفل كله، وبترمي الـ error. نجرّب على ملف مش موجود. نشغّل.
import fs from "node:fs";
import { pipeline } from "node:stream/promises";
try {
await pipeline(
fs.createReadStream("missing.log"),
fs.createWriteStream("copy.log"),
);
} catch (err) {
console.log("pipeline وقع:", err.code);
}
console.log("البرنامج لسه شغال");المخرجات
$ node main.js pipeline وقع: ENOENT البرنامج لسه شغال
ENOENT، يعني الملف مش موجود، اتمسك بـ try، والبرنامج كمّل. القاعدة: أي stream في الـ backend، وصّله بـ pipeline من stream slash promises، ولفّه بـ try. التحدي: تقرير من ملف أكبر من الـ memory. تقرا الـ access log سطر سطر. تعدّ الـ requests لكل status، وتحسب متوسط زمن الرد. وتكتب التقرير في report dot json بـ pipeline. وممنوع readFile على الـ log. الأرقام المطلوبة بالزبط في الكومنت.
اقرا access.log بـ readline و for await، اجمع count و totalMs لكل status، احسب avgMs، واكتب report.json بـ pipeline.
الحل. readline و for await، وأي سطر فاضي نعدّيه. destructuring بنتجاهل فيه أول تلات حاجات بالـ commas، وناخد status و ms. question question equals بتعمل object جديد لو مش موجود. وبعدين نحسب المتوسط، ونكتب بـ pipeline من Readable dot from. نشغّل.
import fs from "node:fs";
import readline from "node:readline";
import { pipeline } from "node:stream/promises";
import { Readable } from "node:stream";
// access.log: id,method,path,status,ms
const lines = readline.createInterface({
input: fs.createReadStream("access.log"),
crlfDelay: Infinity,
});
const stats = {};
for await (const line of lines) {
if (!line) continue;
const [, , , status, ms] = line.split(",");
stats[status] ??= { count: 0, totalMs: 0 };
stats[status].count++;
stats[status].totalMs += Number(ms);
}
const report = {};
for (const [status, s] of Object.entries(stats)) {
report[status] = { count: s.count, avgMs: Math.round(s.totalMs / s.count) };
}
await pipeline(Readable.from([JSON.stringify(report)]), fs.createWriteStream("report.json"));
console.log(fs.readFileSync("report.json", "utf8"));المخرجات
$ node main.js
{"200":{"count":857142,"avgMs":450},"500":{"count":142858,"avgMs":449}}التقرير زي حالات الاختبار. الدرس الجاي: الـ file system والـ paths، والفخاخ الأمنية فيها، زي path traversal.
03 / دروس المسار (122)
- 01أهلًا بيك: يعني إيه backend، والكورس ده ماشي إزاي
- 02الملفات والفولدرات والـ terminal: تتحرك على جهازك زي المبرمجين
- 03Node وأول برنامج: تشغّل وتقرا رسالة الخطأ
- 04القيم والمتغيرات والأنواع: const و let و typeof
- 05القرارات والتكرار: if و === والـ truthy والـ loops
- 06الـ functions: parameters و return والـ arrow functions والـ scope
- 07الـ objects والـ arrays: destructuring و spread و map و filter و reduce
- 08JSON والنصوص والتواريخ: اللغة اللي الـ backend بيتكلم بيها
- 09الـ callbacks والـ closures وأول لمسة async: setTimeout
- 10الـ classes والـ errors: throw و try/catch و stack trace
- 11git: تحفَظ كل خطوة وترجعلها، وما تسرّبش أسرارك
- 12ESM و CommonJS و package exports: Node بيلاقي الـ modules إزاي
- 13الـ Promises و async/await: sequential و parallel والأخطاء والإلغاء
- 14الـ event loop والـ microtasks: Node بيعمل كل حاجة بـ thread واحد إزاي
- 15الـ Streams والـ Backpressure: ملفات أكبر من الـ memoryانت هنا
- 16الـ File System والـ paths: قراية وكتابة صح، ومن غير path traversal
- 17الـ Buffers والبيانات الـ binary: الـ bytes من جُوّه
- 18Crypto APIs والأسرار: random و hash و HMAC و AES-GCM
- 19الـ Worker Threads: شغل CPU تقيل من غير ما توقف الـ server
- 20الـ Errors على مستوى الـ process: operational و programmer و crash-only
- 21الـ Node test runner والـ debugging: tests من غير مكتبات
- 22HTTP من جُوّه: الـ methods والـ status codes والـ headers
- 23Express والـ Routing: الـ params والـ query والترتيب والـ Router
- 24Express 5: إيه اللي اتغيّر، وإزاي تنقل مشروع قديم
- 25الـ Middleware ودورة حياة الـ request جُوّه Express
- 26Validation للمدخلات بـ Zod: ما تصدّقش أي حاجة جاية من برة
- 27تصنيف الأخطاء و Problem Details: شكل واحد لكل الـ errors
- 28الـ CORS والـ Cookies: المتصفح بيحمي المستخدم إزاي
- 29رفع الملفات وحدود الحجم: multer من غير ثغرات
- 30الـ Realtime: Server-Sent Events و WebSockets
- 31OpenAPI والـ API Versioning: عقد مكتوب، وتغيير من غير ما تكسر حد
- 32PostgreSQL: الـ DDL وأنواع البيانات الصح لكل عمود
- 33الـ Constraints: PK و FK و UNIQUE و CHECK — الـ database بتحمي نفسها
- 34الـ Normalization والـ ERD: تقسّم البيانات صح من أول يوم
- 35الـ JOINs والتجميع: INNER و LEFT و GROUP BY و HAVING و window functions
- 36JSONB في PostgreSQL: إمتى تستخدمه، وإزاي تسأله وتعمله index
- 37الـ Indexes من جُوّه: B-tree و GIN و BRIN
- 38Partial و Covering indexes: indexes أصغر وأسرع
- 39الـ Pagination بالـ Keyset: ليه OFFSET بيبطّأ وبيكرر
- 40Full Text Search في Postgres: بحث بالكلمات، بالعربي والإنجليزي
- 41EXPLAIN ANALYZE والـ Planner: اقرا الـ plan وصلّح الـ query
- 42الـ Transactions بـ node-postgres: كله أو ولا حاجة
- 43الـ MVCC ومستويات الـ Isolation: transactions كتير في نفس الوقت
- 44الـ Locks والـ Deadlocks: مين مستني مين
- 45SKIP LOCKED و Job Leasing: Postgres كـ job queue
- 46Row Level Security والـ Multi-tenancy: كل عميل يشوف بياناته بس
- 47Migrations من غير downtime: expand و backfill و contract
- 48الـ Replication والـ Read Replicas: نسخ حية من الـ database
- 49الـ Connection Pooling و PgBouncer: connections أقل، requests أكتر
- 50الـ Partitioning والـ VACUUM والمراقبة: Postgres على المدى الطويل
- 51Redis وأنواع البيانات: strings و hashes و lists و sets و sorted sets
- 52Cache-aside والـ TTL: Redis قدام الـ database
- 53الـ Cache invalidation والـ Stampede: لما الـ key الشهير يموت
- 54Lua والـ Atomicity في Redis: كام أمر كأنهم أمر واحد
- 55الـ Rate Limiting في Redis: fixed window و sliding window و token bucket
- 56الـ Sessions في Redis: تسجيل دخول تقدر تلغيه في أي وقت
- 57Redis Streams والـ Consumer Groups: log بيتوزع على workers
- 58Pub/Sub و BullMQ: إشارات بين الـ instances، وطوابير شغل محترمة
- 59Redis لما يقع: الـ persistence (RDB و AOF) والـ replication
- 60Redis في الإنتاج: الـ ACLs والـ Cluster والمراقبة
- 61تخزين الـ Passwords بـ Argon2id: صح من أول مرة
- 62Session Fixation والـ Rotation: id جديد مع كل صلاحية جديدة
- 63الـ Cookie Flags والـ CSRF: المتصفح بيبعت الـ cookie، فلازم تتأكد مين اللي طلب
- 64الـ XSS والـ Content Security Policy: ما تخليش النص يتحوّل لـ code
- 65الـ OAuth و OpenID Connect و PKCE: login بـ Google من غير ما تشوف الـ password
- 66التأكد من الـ JWT صح: التوقيع والـ claims والـ scopes
- 67الـ BOLA و BFLA: الـ token السليم مش معناه إن الطلب مسموح
- 68الـ RBAC و ABAC والملكية: policy واحدة بدل ifs متفرقة
- 69الـ MFA والـ recovery: التاني factor اللي بجد
- 70الـ Passkeys و WebAuthn: login من غير password وضد الـ phishing
- 71الـ Threat Modeling بـ STRIDE: فكّر زي المهاجم قبل ما تكتب code
- 72الـ SQL Injection والـ Parameterization: الـ data ما تبقاش code
- 73الـ SSRF والـ Egress: ما تخليش الـ server بتاعك يزور الشبكة الداخلية
- 74الـ Security Headers والـ TLS: كل response يقول للـ browser يحمي المستخدم إزاي
- 75توقيع الـ Webhooks والـ Replay: الـ webhook ده جاي فعلًا من Stripe؟
- 76تغيير الأسرار والـ HMAC: إزاي تغيّر مفتاح من غير ما كل حاجة تقع
- 77سلسلة التوريد والـ SBOM: إنت واثق في ألف package ما تعرفهمش؟
- 78الـ Audit والـ Privacy Logs: سجّل مين عمل إيه، من غير ما تسجّل الأسرار
- 79اختبار الأمان و OWASP ASVS: الأمن جُوّه الـ CI، مش audit آخر السنة
- 80الـ Prototype Pollution والـ Resource DoS: request واحد يخلّي الكل admin أو يوقّع الـ server
- 81الـ SLI والـ SLO والـ Error Budget: إمتى تصحّي الـ on-call وإمتى تسيبه نايم
- 82الـ Event Loop Delay والـ ELU: لما Node نفسه يتخنق
- 83الـ Worker Threads والـ CPU Profiling: الشغل التقيل بره الـ event loop، والوقت راح فين
- 84الـ Memory والـ GC والـ Leaks: الـ process اللي بيكبر لحد ما يقع
- 85الـ N+1 Queries والـ DataLoader: صفحة واحدة بمِيّتين query
- 86الـ HTTP Caching والـ Compression: أسرع request هو اللي ما بيوصلش
- 87الـ Load Testing والـ Soak Testing: الـ server بيستحمل قد إيه بجد
- 88الـ Concurrency Limits والـ Bulkheads: dependency بطيئة ما توقعش الـ app كله
- 89الـ Timeouts والـ Retries والـ Circuit Breakers: إزاي تتعامل مع dependency بطيئة أو واقعة
- 90OpenTelemetry والـ Distributed Tracing: الـ request راح فين وضاع وقته فين
- 91Docker Layers والـ Build Context: ليه الـ build بياخد دقيقة وفيه الـ .env بتاعك
- 92Multi-stage Builds و Non-root: image صغيرة ومن غير root
- 93Docker Compose والـ Networks: الـ services بتلاقي بعض إزاي
- 94Docker Volumes: الـ data بتتحفَظ فين
- 95Healthcheck و Restart و Resource Limits: running مش معناها شغّال
- 96BuildKit والـ Build Secrets: الـ token ما يدخلش الـ image
- 97Reverse Proxy و TLS: اللي واقف قدام الـ app
- 98Multi-arch Images والـ Native Modules: اشتغلت عندي
- 99CI/CD و Rollback و Canary: الـ deploy يبقى ممل
- 100Kubernetes من الأول: Pods و Deployments و Services و Probes
- 101Modular Monolith و DDD: حدود واضحة من غير network
- 102Transactional Outbox و Inbox: الـ event ما يضيعش وما يتنفذش مرتين
- 103Sagas: عملية واحدة على تلات services من غير transaction واحدة
- 104CQRS و Event Sourcing: الـ events هي الحقيقة
- 105الـ Queues والـ Brokers: BullMQ و RabbitMQ و Kafka و SQS
- 106Realtime على أكتر من instance: Redis pub/sub و presence و resume
- 107الـ Object Storage والـ Media: presigned URLs و uploads مباشرة
- 108التكامل مع الـ Email والـ Search: retries و webhooks و indexes
- 109GraphQL و gRPC في الإنتاج: contracts و DataLoader و limits و deadlines
- 110Kafka على أكتر من zone و region: الـ replication والـ ISR والـ acks والـ MirrorMaker والـ failover
- 111TypeScript و runtime boundaries: الـ types بتختفي، والـ schemas لأ
- 112ORM ولا SQL: query builders و repositories و migrations و transactions
- 113الـ Serverless من جُوّه: cold starts و freeze و timeouts و connections
- 114الـ Testing Pyramid: unit و integration و e2e على Postgres حقيقية
- 115Contract Testing و Property-Based Testing بـ fast-check
- 116الـ Payments: idempotency و webhooks و refunds و reconciliation
- 117الـ Timezones والـ Internationalization: UTC و DST والـ locales والـ plurals والفلوس
- 118الـ Privacy والـ Data Retention: consent و export و erasure و crypto shredding
- 119الـ ADRs والـ Feature Flags: القرارات المكتوبة والـ rollout من غير deploy
- 120Multi-region active-active: حل الـ conflicts بـ HLC و CRDTs
- 121Readiness و Liveness و Startup Probes: الـ pod جاهز ولا عايش؟
- 122Incident Runbooks: من الـ alert للـ postmortem