0.0.7 • Published 4 months ago

mody v0.0.7

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

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

0.0.7

4 months ago

0.0.6

5 months ago

0.0.3

8 months ago

0.0.5

8 months ago

0.0.4

8 months ago

0.0.2

8 months ago

0.0.1

8 months ago

0.1.0

2 years ago