-1

Từ chối nội cuốn vô nghĩa: 7 thư viện JS giúp code "cứng" hơn

Trong hệ sinh thái JavaScript đang phát triển điên cuồng, nhiều "đổi mới" chỉ là đóng gói lại concept cũ để câu Star trên GitHub. Developer thực thụ cần tool giải quyết pain point production, tăng độ robust của code, và thay đổi workflow — không phải đồ chơi.

image.png

Dưới đây là 7 thư viện đã chứng minh giá trị thực tế, giải quyết validation, queue, cache, runtime, system call và ID generation.


🛡️ Zod: Người gác cổng runtime type validation

TypeScript chỉ check compile-time. Runtime validation thì sao? Zod dùng schema để vừa infer type vừa validate runtime. Sạch hơn Joi/Yup, native TypeScript.

import { z } from "zod";

const envConfig = z.object({
  PORT: z.coerce.number().min(3000).default(3000),
  ADMIN_EMAIL: z.string().email(),
  NODE_ENV: z.enum(["development", "production"]),
});

const processEnv = {
  PORT: "8080",
  ADMIN_EMAIL: "admin@example.com",
  NODE_ENV: "production",
};

const config = envConfig.parse(processEnv);
console.log(config.PORT); // 8080 (number)

📨 BullMQ: Giải pháp queue công nghiệp cho task async

Đừng await task chậm (gửi mail, tạo báo cáo) trên main thread hay dùng setTimeout dễ mất task. BullMQ (Redis-based) hỗ trợ retry, delay, priority, parent-child dependency. Viết lại bằng TypeScript, ổn định hơn Bull cũ.

import { Queue, Worker } from 'bullmq';

const connection = { host: 'localhost', port: 6379 };

const emailQueue = new Queue('email-sending', { connection });

await emailQueue.add('welcome-email', { 
  email: 'user@example.com', 
  subject: 'Welcome!' 
});

const worker = new Worker('email-sending', async job => {
  console.log(`Xử lý ${job.id}: ${job.data.email}`);
  await new Promise(r => setTimeout(r, 1000));
}, { connection });

🔴 ioredis: Redis client chuẩn mực

BullMQ cần Redis. ioredis thống trị với cluster/Sentinel support, Promise-friendly, auto-reconnect thông minh. Giảm gánh nặng ops đáng kể.

import Redis from "ioredis";

const redis = new Redis();

async function cacheUserData(userId, data) {
  await redis.set(`user:${userId}`, JSON.stringify(data), "EX", 3600);
  const cached = await redis.get(`user:${userId}`);
  return cached ? JSON.parse(cached) : null;
}

🆔 Nanoid: Kẻ thay thế UUID hiện đại

UUID dài dòng, không URL-safe. Nanoid sinh ID ngắn hơn, an toàn hơn (crypto random), nhanh hơn. Bundle nhỏ gọn cho distributed system, short link, PK.

import { nanoid, customAlphabet } from 'nanoid';

const id = nanoid(); // "V1StGXR8_Z5jdHi6B-myT" (21 ký tự, URL-safe)

const generateOrderId = customAlphabet('1234567890abcdef', 10);
console.log(generateOrderId()); // "a3f901c8d2"

🐚 Execa: Nói tạm biệt Shell script thủ công

child_process của Node clunky với stream, error, cross-platform. Execa gói gọn, gọi shell như function JS — Promise-ready, không cần escape. Hoàn hảo cho automation/build tool.

import { execa } from 'execa';

async function runBuildProcess() {
  try {
    const { stdout } = await execa('npm', ['run', 'build'], {
      env: { FORCE_COLOR: 'true' }
    });
    console.log('Build output:', stdout);
  } catch (error) {
    console.error('Build fail:', error.exitCode);
  }
}

🤖 ONNX Runtime Web: Chạy AI model ngay trong Node

Không cần Python backend. ONNX Runtime chạy model ML đã train trong môi trường Node.js — low-latency, privacy-focused inference cho image/text/feature.

import ort from 'onnxruntime-node';

async function runInference() {
  const session = await ort.InferenceSession.create('./model.onnx');
  const data = Float32Array.from([1, 2, 3, 4]);
  const tensor = new ort.Tensor('float32', data, [2, 2]);
  const feeds = { input1: tensor };
  const results = await session.run(feeds);
  console.log('Inference:', results.output1.data);
}

🚀 Bun.js: Kẻ phá luật

Bị Anthropic mua lại — đủ nói rồi. Bun tích hợp bundler, tester, package manager. Startup siêu nhanh so với Node. Compatible Node API + native high-perf.

// server.js
Bun.serve({
  port: 3000,
  fetch(req) {
    const url = new URL(req.url);
    return url.pathname === "/" 
      ? new Response("Hello Bun!") 
      : new Response("Not Found", { status: 404 });
  },
});
console.log("http://localhost:3000");

🛠️ Môi trường dev: Nhân tố không thể xem nhẹ

Thư viện tốt rồi, nhưng cài đặt môi trường phát triển local mới là nơi tốn thời gian nhất — switch Node 14 legacy vs Node 22 new feature? Manual nvm/GOPATH ác mộng.

Giới thiệu ServBay — định nghĩa lại local dev như một hệ sinh thái tích hợp:

  • Multi-version hài hòa: Node 12→24 coexist, cách ly từng project.

image.png

  • One-click Bun: Install/run ngay, không CLI phức tạp.

image.png

  • Service stack master: PostgreSQL/Redis/Mongo bật/tắt 1 click.

ServBay không chỉ switch version — nó là nền tảng để focus code thay vì config.


🎯 Kết luận

Bỏ qua hype; chọn tool giải quyết vấn đề thật. Zod bảo vệ type, BullMQ thuần hóa async, Execa tối ưu script, ServBay xóa sổ env chaos.

Năm 2026: Ít bug hơn, env không lỗi, về nhà sớm hơn.


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí