server 
@jsenv/server
helps to write flexible server code with a declarative API.
import { startServer } from "@jsenv/server"
await startServer({
protocol: "http",
port: 8080,
requestToResponse: () => {
return {
status: 200,
headers: {
"content-type": "text/plain",
},
body: "Hello world",
}
},
})
Example
Code starting a server and using node-fetch to send a request on that server:
import fetch from "node-fetch"
import { startServer } from "@jsenv/server"
const server = await startServer({
requestToResponse: () => {
return {
status: 200,
headers: {
"content-type": "text/plain",
},
body: "Hello world",
}
},
})
const response = await fetch(server.origin)
const responseBodyAsText = await response.text()
console.log(responseBodyAsText)
Code starting a server with 2 request handlers:
import { startServer, composeServices } from "@jsenv/server"
const indexService = (request) => {
if (request.ressource === "/") {
return { status: 200 }
}
return null
}
const notFoundService = (request) => {
return { status: 404 }
}
const server = await startServer({
requestToResponse: composeServices({
index: indexService,
otherwise: notFoundService,
}),
})
const fetch = await import("node-fetch")
const responseForOrigin = await fetch(server.origin)
responseForOrigin.status
const responseForFoo = await fetch(`${server.origin}/foo`)
responseForFoo.status
Code starting a server in https:
import { readFileSync } from "node:fs"
import { startServer } from "@jsenv/server"
await startServer({
protocol: "https",
certificate: readFileSyncAsString("./server.crt"),
privateKey: readFileSyncAsString("./server.key"),
allowHttpRequestOnHttps: true,
requestToResponse: (request) => {
const clientUsesHttp = request.origin.startsWith("http:")
return {
status: 200,
headers: {
"content-type": "text/plain",
},
body: clientUsesHttp ? `Welcome http user` : `Welcome https user`,
}
},
})
function readFileSyncAsString(relativeUrl) {
const fileUrl = new URL(relativeUrl, import.meta.url)
return String(readFileSync(fileUrl))
}
Code starting a server for static files:
import { startServer, fetchFileSystem } from "@jsenv/server"
await startServer({
requestToResponse: async (request) => {
const fileUrl = new URL(request.ressource.slice(1), import.meta.url)
const response = await fetchFileSystem(fileUrl, {
...request,
})
return response
},
})
Documentation
Installation
npm install @jsenv/server