typestar

Un servidor HTTP en JavaScript

createServer, un manejador de peticiones y JSON de salida.

import { createServer } from "node:http";

const routes = {
  "/healthz": () => ({ status: "ok" }),
  "/tours": () => ({ tours: ["basics", "async", "node"] }),
};

const server = createServer((request, response) => {
  const handler = routes[new URL(request.url, "http://localhost").pathname];
  if (!handler) {
    response.writeHead(404, { "Content-Type": "application/json" });
    response.end(JSON.stringify({ error: "not found" }));
    return;
  }
  response.writeHead(200, { "Content-Type": "application/json" });
  response.end(JSON.stringify(handler()));
});

server.listen(0, () => {
  console.log("listening on", server.address().port > 0);
  server.close();
});

Cómo funciona

  1. El manejador recibe la petición y la respuesta.
  2. Escribe el estado y las cabeceras antes del cuerpo.
  3. server.close deja de aceptar y luego termina lo que está en vuelo.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
22
Caracteres a escribir
644
Tokens
179
Ritmo de tres estrellas
110 tpm

Al ritmo de tres estrellas de 110 tokens por minuto, este intento toma unos 98 segundos.

Escribe este fragmento

Paso 1 de 3 en Red; paso 12 de 18 en Node.js.

← Anterior Siguiente →