Node.js hiện đại: npm, --watch, --env-file, node:test và TypeScript
Node.js ngày nay có sẵn rất nhiều thứ mà trước đây phải cài gói ngoài: fetch, watch mode, đọc .env, test runner, chạy TypeScript…
Khởi tạo dự án
mkdir my-app && cd my-app
npm init -y
npm pkg set type=module # dùng ES Modules
npm install zod # dependency
npm install -D eslint prettier # devDependency{
"name": "my-app",
"type": "module",
"engines": { "node": ">=24" },
"scripts": {
"dev": "node --watch --env-file=.env src/index.js",
"start": "node src/index.js",
"test": "node --test"
}
}npm run dev(hoặcnode --run dev— nhanh hơn, không qua npm).- Commit
package-lock.jsonđể mọi người cài đúng phiên bản; trên CI dùngnpm ci. npx <gói>chạy công cụ không cần cài toàn cục.
Thay cho các gói quen thuộc
| Trước đây | Giờ có sẵn |
|---|---|
nodemon | node --watch |
dotenv | node --env-file=.env hoặc process.loadEnvFile() |
node-fetch, axios | fetch toàn cục |
jest, mocha (cho dự án đơn giản) | node --test + node:test |
ts-node (cho script đơn giản) | Chạy file .ts trực tiếp |
chalk | util.styleText |
yargs (cho CLI đơn giản) | util.parseArgs |
uuid | crypto.randomUUID() |
Đọc biến môi trường
DATABASE_URL=postgres://localhost/shop
PORT=3000const port = Number(process.env.PORT ?? 3000);Test runner có sẵn
import { describe, it } from "node:test";
import assert from "node:assert/strict";
import { totalPrice } from "./cart.js";
describe("totalPrice", () => {
it("cộng giá × số lượng", () => {
assert.equal(totalPrice([{ price: 100, qty: 2 }, { price: 50, qty: 1 }]), 250);
});
it("giỏ rỗng trả về 0", () => {
assert.equal(totalPrice([]), 0);
});
it("ném lỗi khi số lượng âm", () => {
assert.throws(() => totalPrice([{ price: 1, qty: -1 }]), RangeError);
});
});node --test # tự tìm các file *.test.js, *.spec.js...
node --test --watch # chạy lại khi sửa
node --test --experimental-test-coverageChạy TypeScript trực tiếp
Node.js hiện đại có thể chạy file .ts bằng cách xóa phần kiểu (type stripping) — không cần build:
export function sum(numbers: number[]): number {
return numbers.reduce((a, b) => a + b, 0);
}node src/sum.tsLưu ý:
- Node không kiểm tra kiểu — vẫn chạy
tsc --noEmit(hoặc dựa vào IDE/CI) để bắt lỗi kiểu. - Chỉ hỗ trợ cú pháp "xóa được": không dùng
enum,namespace, parameter properties trong constructor. Bật"erasableSyntaxOnly": truetrongtsconfig.jsonđể TypeScript cảnh báo. - Import phải ghi rõ đuôi
.ts.
Một HTTP server tối giản
import { createServer } from "node:http";
const server = createServer(async (req, res) => {
if (req.method === "GET" && req.url === "/health") {
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true }));
}
res.writeHead(404).end();
});
server.listen(process.env.PORT ?? 3000, () => console.log("Server đang chạy"));Dự án thật thường dùng framework như Fastify, Hono, Express hoặc NestJS.
TIP
Luôn dùng bản LTS của Node.js cho production, và nâng cấp định kỳ — mỗi bản LTS chỉ được hỗ trợ bảo mật trong một thời gian giới hạn.
Comments