Edge-Style http server for NodeJS using Fetch API.
npm install mody
import { serve } from "mody";
serve((req) => new Response("Hello Mody"));
// serve(handler, { port: 8000 });
Mody is based on Fetch API
The Request interface of the Fetch API represents a resource request.
The Response interface of the Fetch API represents the response to a request.
import { serve } from "mody";
serve(() => Response.json({ name: "john" }));
import { serve } from "mody";
import { writeFile } from "node:fs/promises";
import { Buffer } from "node:buffer";
serve(async (req) => {
const url = new URL(req.url);
if (req.method === "POST" && url.pathname === "/") {
const formData = await req.formData();
const file = formData.get("file") as File | null;
if (file) {
const ab = await file.arrayBuffer();
await writeFile(file.name, Buffer.from(ab));
return new Response("Success upload");
}
return new Response("Field file is required", { status: 422 });
}
return new Response(null, { status: 404 });
});
import { serve } from "mody";
serve((req) => {
const url = new URL(req.url);
if (url.pathname === "/") {
return new Response("home");
}
if (url.pathname === "/redirect") {
return Response.redirect(new URL("/", url.origin));
}
return new Response(null, { status: 404 });
});
import { serve } from "mody";
serve((req) => {
let int;
const stream = new ReadableStream({
start(controller) {
int = setInterval(() => {
controller.enqueue(`data: hello, mody\n\n`);
}, 1000);
},
cancel() {
clearInterval(int);
},
});
return new Response(stream, {
headers: { "content-type": "text/event-stream" },
});
});
See More Examples