mody
TypeScript icon, indicating that this package has built-in type declarations

0.0.7 • Public • Published

Mody

Edge-Style http server for NodeJS using Fetch API.

GitHub npm bundlejs

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

License

MIT

Package Sidebar

Install

npm i mody

Weekly Downloads

25

Version

0.0.7

License

MIT

Unpacked Size

23.6 kB

Total Files

18

Last publish

Collaborators

  • herudi