Node.js พึ่งพา design patterns จำนวนหนึ่งที่เข้ากับ module system, async model และ streaming I/O ของมัน สิ่งที่พบบ่อยที่สุดที่นักพัฒนา backend ทุกคนควรจดจำได้:
Node.js พึ่งพา design patterns จำนวนหนึ่งที่เข้ากับ module system, async model และ streaming I/O ของมัน สิ่งที่พบบ่อยที่สุดที่นักพัฒนา backend ทุกคนควรจดจำได้:
module.exports / export โดยเก็บส่วนภายในไว้เป็น private เป็นรากฐานของการจัดระเบียบ code ใน Node// db.js — ทุก `require("./db")` จะได้ pool เดียวกันนี้ (singleton ผ่าน module cache)
const pool = createPool(process.env.DATABASE_URL);
module.exports = pool;
function createLogger(kind) {
return kind === "json" ? new JsonLogger() : new TextLogger();
}
EventEmitter, streams และ core module ส่วนใหญ่ใช้มันconst { EventEmitter } = require("node:events");
const bus = new EventEmitter();
bus.on("order:paid", (o) => sendReceipt(o));
bus.emit("order:paid", order);
(ctx, next) ทำให้เป็นที่นิยมโดย Express/Koa เยี่ยมสำหรับเรื่องที่ตัดขวาง (auth, logging, validation)app.use((req, res, next) => { req.startedAt = Date.now(); next(); });
const { pipeline } = require("node:stream/promises");
await pipeline(fs.createReadStream("in"), gzip(), fs.createWriteStream("out.gz"));
| ความต้องการ | Pattern |
|---|---|
| ทรัพยากรที่ใช้ร่วมกันหนึ่งเดียว | Singleton (module cache) |
สร้าง objects, ซ่อน new | Factory |
| ตอบสนองต่อ events แบบ async | Observer / EventEmitter |
| logic ของ request ที่ตัดขวาง | Middleware |
| ประมวลผลข้อมูลใหญ่อย่างปลอดภัย | Streams / pipeline |
| dependencies ที่ทดสอบได้ แยกส่วน | Dependency Injection |
Patterns คือคำศัพท์ร่วมกัน: การพูดว่า "config เป็น singleton ที่ cache ตาม module" หรือ "auth เป็น middleware" สื่อสารการออกแบบได้ในไม่กี่คำ core ของ Node เอง (EventEmitter, streams, module system) สร้างขึ้นจากสิ่งเหล่านี้ ดังนั้นการจดจำมันจึงช่วยให้คุณอ่าน framework และจัดโครงสร้าง service ของคุณเองได้ ผู้สัมภาษณ์ใช้คำถามนี้เพื่อตรวจสอบว่าคุณไม่ได้แค่ต่อ callback แบบเฉพาะกิจ แต่เอื้อมไปหา pattern ที่เหมาะสม — และรู้ trade-off ของมัน เช่น singleton ทำให้ global state ทดสอบได้ยากขึ้น
คลังคำถามสัมภาษณ์งาน IT พร้อมคำตอบโดยละเอียด — ตั้งแต่ระดับ Junior ถึง Senior
บริจาค