@jsenv/server
v15.3.3
Published
Write your Node.js server using pure functions
Downloads
1,574
Readme
server
@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
- Handling requests
- Handling errors
- Server timing
- CORS
- https
- Serving files
- Content negotiation
- Websocket
- Server Sent Events
- Cluster
- Http2 push
Installation
npm install @jsenv/server