Getting Started
Http4ts is a minimal HTTP library for JavaScript environments (Node.js, Deno etc.) implementing the pattern of server as a function. In http4ts, a server is just a function with the following signature:
type HttpHandler = (req: HttpRequest) => HttpResponse | Promise<HttpResponse>;
See the simple server application examples, one for deno and another for Node.js.
Installation
- Node.js
- Deno
Http4ts is available via npm. You can install it using the following command:
npm install http4ts
#
Binding to Node.jsIn order to use this library in Node.js, you have to bind the HttpHandler
to the Node.js HTTP server. Http4ts supplies a function called toNodeRequestListener
to bind an HttpHandler
to the Node.js server.
import * as http from "http";
import { HttpRequest, toNodeRequestListener, OK} from "http4ts";
async function handler(req: HttpRequest) { // 1. Write the handler as a function that returns response return OK({ body: "Hello world!" });}
const server = http.createServer( toNodeRequestListener(handler) // 2. Connect the handler to the node.js server);
const hostname = "127.0.0.1";const port = 3000;
server.listen(port, hostname, () => { // 3. Start your node server as you were before console.log(`Server running at http://${hostname}:${port}/`);});
In Deno, it is possible to import the library via its url. You can use Http4ts by importing the following url:
https://deno.land/x/http4ts/mod.ts
#
Binding to DenoIn order to use this library in Deno, you have to bind the HttpHandler
to the Deno HTTP server. Http4ts supplies a function called toDenoRequestListener
to bind an HttpHandler
to the server.
import { listenAndServe } from "https://deno.land/std/http/server.ts";
import { HttpRequest, toDenoRequestListener, OK} from "https://deno.land/x/http4ts/mod.ts";
async function handler(req: HttpRequest) { // 1. Write the handler as a function that returns response return OK({ body: "Hello world!" });}
console.log("Listening on http://localhost:8000");await listenAndServe({ port: 8000 }, toDenoRequestListener(handler));
You can also run this example by executing the following command in your shell environment:
deno run --allow-net=0.0.0.0:8000 https://deno.land/x/http4ts/examples/readme-example.ts
#
Example ProjectWe have implemented the famous realworld backend for you to compare the code with other http libraries in node.js. You can find this example here.