Skip to content

Readline Module

ทำไมต้องใช้ readline?

readline คือเครื่องมือสำคัญสำหรับการสร้างโปรแกรม CLI ที่โต้ตอบกับผู้ใช้ เช่น การรับ input, การถาม-ตอบ, หรือการสร้าง wizard

  • ถ้าเขียน CLI แบบที่ต้องรับค่าจากผู้ใช้ (เช่น npm init, git commit) จะใช้ readline เพื่อให้ผู้ใช้กรอกข้อมูลได้สะดวก
  • ถ้าไม่ใช้ readline จะต้องอ่านข้อมูลจาก stdin ด้วยวิธีที่ซับซ้อนและไม่สะดวก
  • readline จัดการเรื่องการอ่านบรรทัด, ปิดโปรแกรม, และ event ต่าง ๆ ให้ครบจบในตัว เหมาะกับมือใหม่ที่อยากสร้าง CLI ที่ดูดีและใช้งานง่าย

แนะนำ Readline module

readline เป็น built-in module สำหรับรับ input จากผู้ใช้ทาง command-line (stdin) และแสดงผลลัพธ์ (stdout) เหมาะสำหรับสร้าง CLI ที่โต้ตอบกับผู้ใช้ เช่น wizard, prompt, หรือ interactive tool


การสร้างอินเทอร์เฟซรับค่าจากผู้ใช้

readline.createInterface(options)

สร้าง interface สำหรับรับ input

js
const readline = require("readline");
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

การรับค่าด้วย question()

rl.question(prompt, callback)

แสดงคำถามและรับคำตอบจากผู้ใช้

js
rl.question("ชื่อของคุณคืออะไร? ", answer => {
  console.log(`สวัสดี, ${answer}!`);
  rl.close();
});

การอ่านค่าทีละบรรทัด (line event)

js
rl.on("line", (input) => {
  console.log(`คุณพิมพ์: ${input}`);
  if (input === "exit") rl.close();
});

เคล็ดลับและกรณีใช้งานจริง

  • ใช้ readline สำหรับ wizard, interactive prompt, หรือ config CLI
  • สามารถใช้ร่วมกับ async/await ได้ โดย promisify rl.question
  • ใช้ readline.emitKeypressEvents(process.stdin) เพื่อจับ keypress

ตัวอย่างการใช้งานจริง: สร้าง CLI ที่รับค่าหลายบรรทัด

js
const readline = require("readline");
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
console.log("พิมพ์ข้อความ (exit เพื่อออก):");
rl.on("line", line => {
  if (line === "exit") rl.close();
  else console.log(">>", line);
});

อ้างอิง