Skip to content

Util Module

ทำไม util ถึงสำคัญกับ CLI?

เวลาทำ CLI จริง ๆ จะเจอปัญหาเช่น ต้องแปลงฟังก์ชัน callback เป็น promise, ต้อง format string, หรือ debug object ให้อ่านง่าย util ช่วยให้ชีวิตง่ายขึ้นมาก เหมาะกับมือใหม่ที่อยากเขียน CLI แบบ modern

  • util.promisify ช่วยให้ใช้ async/await กับโค้ดเก่าได้
  • util.format ช่วยสร้างข้อความ log ที่อ่านง่าย
  • util.inspect ช่วย debug object ขนาดใหญ่

แนะนำ Util module

util เป็น module รวมฟังก์ชันช่วยเหลือเช่น การแปลง callback เป็น promise, การ format string, การ inspect object ฯลฯ


การแปลง callback เป็น promise

util.promisify(fn)

แปลงฟังก์ชัน callback เป็น promise เพื่อใช้กับ async/await

js
const util = require("util");
const fs = require("fs");
const readFile = util.promisify(fs.readFile);
readFile("file.txt", "utf8").then(data => console.log(data));

การ format string

util.format(format[, ...args])

สร้าง string แบบ format

js
const util = require("util");
console.log(util.format("%s:%d", "port", 8080));

การ inspect object

util.inspect(object[, options])

แสดง object ให้อ่านง่ายขึ้น (เหมาะกับ debug)

js
const util = require("util");
console.log(util.inspect({ foo: 123, bar: [1, 2, 3] }, { colors: true }));

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

  • เขียน CLI ที่ต้อง async/await กับฟังก์ชันเก่า (callback)
  • สร้างข้อความ log แบบ format
  • ใช้ inspect debug object ให้อ่านง่าย

ตัวอย่าง: promisify + format

js
const util = require("util");
const fs = require("fs");
const readFile = util.promisify(fs.readFile);
readFile("file.txt", "utf8").then(data => {
  console.log(util.format("File content: %s", data));
});

อ้างอิง