Skip to content

util

util เป็นโมดูลในตัวของ Node.js ที่ให้ฟังก์ชันอรรถประโยชน์ต่างๆ เพื่อสนับสนุนการเขียนโค้ด เช่น การแปลง callback เป็น promise, การตรวจสอบชนิดข้อมูล, การจัดรูปแบบข้อความ เป็นต้น

import { promisify, inspect, types, format } from 'node:util';

APIคำอธิบายลักษณะคำอธิบายเพิ่มเติม
util.promisify()แปลงฟังก์ชัน callback-style เป็น promiseFunctionใช้แปลง API แบบเดิมให้ใช้งานกับ async/await ได้
util.inspect()แปลงอ็อบเจกต์เป็นสตริงสำหรับตรวจสอบFunctionช่วยแสดงโครงสร้างข้อมูลที่ซับซ้อนในรูปแบบที่อ่านง่าย
util.typesวิธีตรวจสอบชนิดข้อมูลขั้นสูงObjectมีเมธอดสำหรับตรวจสอบชนิดข้อมูลพิเศษ เช่น Buffer, Date, Promise
util.format()จัดรูปแบบข้อความคล้าย printfFunctionใช้แทรกค่าตัวแปรในข้อความ คล้าย console.log
util.deprecate()ทำเครื่องหมายฟังก์ชันว่าเลิกใช้Functionแสดงคำเตือนเมื่อมีการใช้ฟังก์ชันที่ไม่แนะนำให้ใช้แล้ว
util.callbackify()แปลงฟังก์ชัน promise-based เป็น callbackFunctionทำงานตรงข้ามกับ promisify ใช้กับ API ที่ต้องการแบบ callback
util.debuglog()สร้างฟังก์ชัน debug ตามสภาพแวดล้อมFunctionทำงานเฉพาะเมื่อตั้งค่าตัวแปรสภาพแวดล้อม NODE_DEBUG
util.inherits()ทำให้คลาสสืบทอดคุณสมบัติจากคลาสอื่นFunctionวิธีแบบเก่า ปัจจุบันแนะนำให้ใช้ class และ extends ของ ES6
util.isDeepStrictEqual()เปรียบเทียบความเท่ากันแบบลึกFunctionตรวจสอบความเท่ากันของโครงสร้างข้อมูลซับซ้อนแบบ strict equality

ตัวอย่าง

การแปลงฟังก์ชัน Callback เป็น Promise ด้วย promisify

js
import * as fs from "node:fs";
import { promisify } from "node:util";

// แปลงฟังก์ชัน fs.readFile แบบ callback ให้เป็นแบบ Promise
const readFilePromise = promisify(fs.readFile);

// ใช้งานกับ async/await
async function readConfig() {
  try {
    // อ่านไฟล์โดยไม่ต้องใช้ callback
    const data = await readFilePromise("config.json", "utf8");
    const config = JSON.parse(data);
    console.log("ข้อมูลคอนฟิก:", config);
    return config;
  } catch (err) {
    console.error("เกิดข้อผิดพลาด:", err);
    throw err;
  }
}

// เรียกใช้ฟังก์ชัน
readConfig().catch(err => {
  console.error("ไม่สามารถอ่านคอนฟิกได้:", err.message);
});

การตรวจสอบโครงสร้างข้อมูลด้วย inspect

js
import { inspect } from "node:util";

// สร้างอ็อบเจกต์ซับซ้อน
const complexObject = {
  user: {
    name: "ธนพล",
    age: 28,
    skills: ["JavaScript", "Node.js", "React"],
    contact: {
      email: "[email protected]",
      phone: null,
      address: undefined,
    },
  },
  metadata: {
    createdAt: new Date(),
    id: Buffer.from("abc123"),
  },
};

// แสดงผลแบบปกติจะไม่แสดงข้อมูลบางอย่าง (เช่น undefined)
// และมีข้อจำกัดในการแสดงโครงสร้างซับซ้อน
console.log("แบบปกติ:", complexObject);

// ใช้ inspect ช่วยแสดงข้อมูลละเอียดขึ้น
console.log("ใช้ inspect:");
// กำหนดการแสดงผลได้ เช่น colors ใส่สี, depth ความลึกที่แสดง,
// showHidden แสดงข้อมูลซ่อน, compact ย่อขนาด
console.log(inspect(complexObject, {
  colors: true,
  depth: 3,
  showHidden: false,
  compact: false,
}));

การตรวจสอบชนิดข้อมูลด้วย util.types

js
import { types } from "node:util";

// ตรวจสอบชนิดข้อมูลต่างๆ
console.log("ตรวจสอบชนิดข้อมูล:");
console.log(`[] เป็น Array: ${types.isArray([])}`);
console.log(`'abc' เป็น RegExp: ${types.isRegExp("abc")}`);
console.log(`new Date() เป็น Date: ${types.isDate(new Date())}`);
console.log(
  `Promise.resolve() เป็น Promise: ${types.isPromise(Promise.resolve())}`,
);
console.log(
  `Buffer.from('') เป็น Uint8Array: ${types.isUint8Array(Buffer.from(""))}`,
);

// ตรวจสอบชนิดข้อมูลที่ยากขึ้น
const buffer = Buffer.from("hello");
const uint8Array = new Uint8Array(5);

console.log(`Buffer เป็น Uint8Array: ${buffer instanceof Uint8Array}`); // true
console.log(`Uint8Array เป็น Buffer: ${uint8Array instanceof Buffer}`); // false

// ใช้ util.types สำหรับการตรวจสอบแบบเฉพาะเจาะจงมากขึ้น
console.log(`Buffer เป็น Buffer: ${types.isBuffer(buffer)}`); // true
console.log(`Uint8Array เป็น Buffer: ${types.isBuffer(uint8Array)}`); // false

การจัดรูปแบบข้อความด้วย format

js
import { format } from "node:util";

// format ทำงานคล้ายกับ printf ในภาษา C
const name = "มานี";
const age = 25;
const balance = 1234.5678;

// รูปแบบพื้นฐาน - แทนที่ %s ด้วยสตริง, %d ด้วยตัวเลข, %j ด้วย JSON
const message1 = format("สวัสดี %s อายุ %d ปี", name, age);
console.log(message1); // สวัสดี มานี อายุ 25 ปี

// รูปแบบ object - แทนที่ %o หรือ %O ด้วยการแสดงอ็อบเจกต์
const user = { name, age, active: true };
const message2 = format("ข้อมูลผู้ใช้: %o", user);
console.log(message2);

// รูปแบบตัวเลขทศนิยม - แทนที่ %f
const message3 = format("ยอดเงิน: %f บาท", balance);
console.log(message3); // ยอดเงิน: 1234.5678 บาท

// รูปแบบเปอร์เซ็นต์ - แทนที่ %% ด้วยเครื่องหมาย %
const percent = 75;
const message4 = format("ความคืบหน้า: %d%% เสร็จแล้ว", percent);
console.log(message4); // ความคืบหน้า: 75% เสร็จแล้ว

การทำเครื่องหมายฟังก์ชันที่เลิกใช้ด้วย deprecate

js
import { deprecate } from "node:util";

// ฟังก์ชันเดิมที่กำลังจะเลิกใช้
function oldFunction(x, y) {
  return x + y;
}

// สร้างเวอร์ชันใหม่ที่มีการแจ้งเตือน
const deprecatedFunction = deprecate(
  oldFunction,
  "oldFunction() เลิกใช้แล้ว กรุณาใช้ newFunction() แทน",
  "DEP001", // รหัสเตือน (optional)
);

// ฟังก์ชันใหม่ที่ควรใช้แทน
function newFunction(x, y) {
  return x + y;
}

// เมื่อเรียกใช้งานจะแสดงคำเตือน
console.log(deprecatedFunction(5, 10)); // แสดงผล 15 พร้อมกับคำเตือน
console.log(newFunction(5, 10)); // แสดงผล 15 โดยไม่มีคำเตือน