mody
v0.0.7
Published
Edge-Style http server for node
Downloads
48
Maintainers
Readme
Mody
Edge-Style http server for NodeJS using Fetch API.
Install
npm install mody
Usage
import { serve } from "mody";
serve((req) => new Response("Hello Mody"));
// serve(handler, { port: 8000 });
Fetch Handler
Mody is based on Fetch API
Request
The Request interface of the Fetch API represents a resource request.
Response
The Response interface of the Fetch API represents the response to a request.
Examples
Send Json
import { serve } from "mody";
serve(() => Response.json({ name: "john" }));
Upload File
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 });
});
Redirect
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 });
});
Server Sent Event (SSE)
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