H
HTTP Server
Create a type-safe HTTP server using Node.js built-in modules.
Code
typescript
1import { createServer, IncomingMessage, ServerResponse } from "http";2 3// Route handler type4type RouteHandler = (5 req: IncomingMessage,6 res: ServerResponse7) => void | Promise<void>;8 9// Simple router10class Router {11 private routes: Map<string, Map<string, RouteHandler>> = new Map();12 13 get(path: string, handler: RouteHandler): void {14 this.addRoute("GET", path, handler);15 }16 17 post(path: string, handler: RouteHandler): void {18 this.addRoute("POST", path, handler);19 }20 21 private addRoute(method: string, path: string, handler: RouteHandler): void {22 if (!this.routes.has(method)) {23 this.routes.set(method, new Map());24 }25 this.routes.get(method)!.set(path, handler);26 }27 28 handle(req: IncomingMessage, res: ServerResponse): void {29 const method = req.method || "GET";30 const path = req.url || "/";31 32 const handler = this.routes.get(method)?.get(path);33 34 if (handler) {35 handler(req, res);36 } else {37 res.statusCode = 404;38 res.end(JSON.stringify({ error: "Not found" }));39 }40 }41}42 43// JSON response helper44function json(res: ServerResponse, data: unknown, status = 200): void {45 res.statusCode = status;46 res.setHeader("Content-Type", "application/json");47 res.end(JSON.stringify(data));48}49 50// Create router and add routes51const router = new Router();52 53router.get("/", (req, res) => {54 json(res, { message: "Welcome to the API" });55});56 57router.get("/health", (req, res) => {58 json(res, { status: "healthy", timestamp: new Date().toISOString() });59});60 61router.get("/users", (req, res) => {62 const users = [63 { id: 1, name: "Alice" },64 { id: 2, name: "Bob" },65 ];66 json(res, users);67});68 69// Create and start server70const server = createServer((req, res) => {71 router.handle(req, res);72});73 74const PORT = process.env.PORT || 3000;75 76server.listen(PORT, () => {77 console.log(`Server running at http://localhost:${PORT}`);78});Run this example locally
$ npx ts-node node/http-server.ts