@jsenv/server

15.2.2 • Public • Published

server npm package

@jsenv/server helps to write flexible server code with a declarative API.

import { startServer } from "@jsenv/server";

await startServer({
  port: 8080,
  services: [
    {
      handleRequest: () => {
        return {
          status: 200,
          headers: {
            "content-type": "text/plain",
          },
          body: "Hello world",
        };
      },
    },
  ],
});

Examples

Code starting a server with 2 request handlers:

/*
 * starts a server which:
 * - when requested at "/"
 *   -> respond with 200
 * - otherwise
 *   -> respond with 404
 */
import { startServer, composeServices } from "@jsenv/server";

const server = await startServer({
  services: [
    {
      name: "index",
      handleRequest: (request) => {
        if (request.resource === "/") {
          return { status: 200 };
        }
        return null;
      },
    },
    {
      name: "otherwise",
      handleRequest: () => {
        return { status: 404 };
      },
    },
  ],
});

const fetch = await import("node-fetch");
const responseForOrigin = await fetch(server.origin);
responseForOrigin.status; // 200

const responseForFoo = await fetch(`${server.origin}/foo`);
responseForFoo.status; // 404

Code starting a server in https:

import { readFileSync } from "node:fs";
import { startServer } from "@jsenv/server";

await startServer({
  https: {
    certificate: readFileSync(new URL("./server.crt", import.meta.url), "utf8"),
    privateKey: readFileSync(new URL("./server.key", import.meta.url), "utf8"),
  },
  allowHttpRequestOnHttps: true,
  services: [
    {
      handleRequest: (request) => {
        const clientUsesHttp = request.origin.startsWith("http:");

        return {
          status: 200,
          headers: {
            "content-type": "text/plain",
          },
          body: clientUsesHttp ? `Welcome http user` : `Welcome https user`,
        };
      },
    },
  ],
});

Code starting a server for static files:

import { startServer, fetchFileSystem } from "@jsenv/server";

await startServer({
  services: [
    {
      handleRequest: async (request) => {
        const fileUrl = new URL(request.resource.slice(1), import.meta.url);
        const response = await fetchFileSystem(fileUrl, request);
        return response;
      },
    },
  ],
});

Documentation

Installation

npm install @jsenv/server

Readme

Keywords

none

Package Sidebar

Install

npm i @jsenv/server

Weekly Downloads

128

Version

15.2.2

License

MIT

Unpacked Size

153 kB

Total Files

53

Last publish

Collaborators

  • jsenv-admin
  • dmail