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…
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ặc node --run dev — nhanh hơn, không qua npm).package-lock.json để mọi người cài đúng phiên bản; trên CI dùng npm ci.npx <gói> chạy công cụ không cần cài toàn cụ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() |
DATABASE_URL=postgres://localhost/shop
PORT=3000const port = Number(process.env.PORT ?? 3000);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:
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-coverageNode.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 ý:
tsc --noEmit (hoặc dựa vào IDE/CI) để bắt lỗi kiểu.enum, namespace, parameter properties trong constructor. Bật "erasableSyntaxOnly": true trong tsconfig.json để TypeScript cảnh báo..ts.import { createServer } from "node:http";
const server = createServer(async (req, res) => {
if (req.method === "GET" && req.url === "/health") {
res.writeHead(200, { "Content-Type":
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