Created
July 4, 2024 23:59
-
-
Save arisris/966f7e514d0be9b9af66fb886bac1569 to your computer and use it in GitHub Desktop.
Run Hono On Node.js 22
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { Hono } from "hono"; | |
| import { compress } from "hono/compress"; | |
| import { streamSSE } from "hono/streaming"; | |
| import { createServer } from "node:http"; | |
| const app = new Hono(); | |
| app.get("/", compress({ encoding: "gzip" }), (c) => { | |
| return c.html("<h1>Hello, World!</h1>"); | |
| }); | |
| app.get("/json", (c) => { | |
| return c.json({ hello: "world" }); | |
| }); | |
| app.get("/sse", (c) => { | |
| let size = 10; | |
| return streamSSE(c, async (stream) => { | |
| while (size > 0) { | |
| size -= 1; | |
| await new Promise((resolve) => setTimeout(resolve, 500)); | |
| stream.writeSSE({ data: `Hello, World! ${size}` }); | |
| } | |
| }); | |
| }); | |
| function convertReqToStandardRequest(req) { | |
| const host = req.headers["host"]; | |
| const url = req.url; | |
| const protocol = req.connection.encrypted ? "https" : "http"; | |
| const fullUrl = host ? `${protocol}://${host}${url}` : url; | |
| const method = req.method; | |
| const headers = {}; | |
| for (const [key, value] of Object.entries(req.headers)) { | |
| headers[key.toLowerCase()] = value; | |
| } | |
| let body; | |
| if (method !== "GET" && method !== "HEAD") { | |
| if (req.headers["content-type"]?.includes("json")) { | |
| try { | |
| body = JSON.parse(req.body); | |
| } catch (error) { | |
| console.error("Error parsing JSON body:", error); | |
| body = null; | |
| } | |
| } else { | |
| body = req.rawBody || ""; | |
| } | |
| } | |
| return new Request(fullUrl, { method, headers: new Headers(headers), body }); | |
| } | |
| const server = createServer(async (req, res) => { | |
| const response = await app.fetch(convertReqToStandardRequest(req), {}, {}); | |
| for (const [key, value] of response.headers) { | |
| res.setHeader(key, value); | |
| } | |
| res.statusCode = response.status; | |
| res.statusMessage = response.statusText; | |
| const body = response.body?.getReader(); | |
| while (!!body) { | |
| const { done, value } = await body.read(); | |
| if (done) { | |
| break; | |
| } | |
| res.write(value); | |
| } | |
| res.end(); | |
| }); | |
| server.listen(3000, () => { | |
| console.log("Server running at http://localhost:3000/"); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment