Git Product home page Git Product logo

http-server's Introduction

@pilcrowjs/http-server

An experimental HTTP framework.

npm install @pilcrowjs/http-server
import { App } from "@pilcrowjs/http-server";
import { serve } from "@pilcrowjs/http-server/node";

const app = new App().get("/", async (request, response) => {
	response.sendText(200, "Hello world!");
});

serve(app, 8000);

Basic usage

import { App } from "@pilcrowjs/http-server";
import { serve } from "@pilcrowjs/http-server/node";

const app = new App()
	.get("/", async (request, response) => {
		const cookie = request.getCookie(name);
		const header = requests.header.get(field);

		const body = request.body; // ReadableStream<Uint8Array>
		const body = await request.text();
		const body = await request.json();
		const body = await request.buffer(); // Uint8Array

		response.setCookie(name, value, attributes);
		response.setHeader(field, value);
		response.addHeader(field, value); // allows you to set duplicate headers - mostly for 'Set-Cookie' header

		//  'return' not required
		return response.sendText(status, data); // text/plain
		return response.setJSON(status, object); // application/json
		return response.sendHTML(status, html); // text/html
	})
	.all()
	.post()
	.put(); // ... etc

serve(app, 8000);

Streaming

const app = new App().get("/", async (request, response) => {
	response.headers.set("Content-Type", "text/plain");
	response.headers.set("X-Content-Type-Options", "nosniff");
	// send status + headers
	const body = response.writeHead(200);
	const interval = setInterval(() => body.writeString("hello\n"), 500);
	await response.closed; // resolves when connection closes
	clearInterval(interval);
});

Middleware

Use ServerRequest.locals to share state between middleware and request handlers.

app.use((request, response, next) => {
    request.locals.message = "hello"
	await next(); // go to next middleware or request handler
});

declare "module" {
    interface Locals {
        message: string
    }
}

Web API

import { App } from "@pilcrowjs/http-server";
import { getResponse } from "@pilcrowjs/http-server/web";

const app = new App();

const response = await getResponse(request as Request, app);

API reference

App

interface App {
	use(middleware: Middleware): this; // use middleware
	get(middleware: Middleware): this;
	post(middleware: Middleware): this;
	delete(middleware: Middleware): this;
	put(middleware: Middleware): this;
	options(middleware: Middleware): this;
	head(middleware: Middleware): this;
	trace(middleware: Middleware): this;
	all(middleware: Middleware): this;
}

type Middleware = (
	request: ServerRequest,
	response: ServerResponse,
	next: () => Promise<void> // goto next handler
) => Promise<void> | void;

type RequestHandler = (request: ServerRequest, response: ServerResponse) => Promise<void> | void;

ServerHeaders

interface ServerHeaders {
	get(field: string): string | null;
	getAll(field: string): string[];
	set(field: string, value: string): void; // replace existing headers
	add(field: string, value): void; // allow duplicate headers (e.g. 'Set-Cookie')
	delete(field: string): void;
	entries(): IterableIterator;
}

ServerRequest

interface ServerRequest {
	pathname: string;
	query: URLSearchParams;
	method: string;
	headers: ServerHeaders;
	body: ReadableStream<Uint8Array>;
	locals: Locals;

	text(): Promise<string>;
	json(): Promise<unknown>;
	buffer(): Promise<Uint8Array>;
	getCookie(name: string): string | null;
}

ServerResponse

interface ServerResponse {
	headers: ServerHeaders;

	writeHead(status: number): ResponseBodyWriter; // sends status and headers

	sendText(status: number, data: string): void; // `writeHead()` + text/plain
	sendJSON(status: number, data: object): void; // `writeHead()` + application/json
	sendHTML(status: number, data: string): void; // `writeHead()` + text/html

	setCookie(name: string, value: string, attributes?: CookieAttributes): this;
	setHeader(field: string, value: string): this; // ServerHeaders.set()
	addHeader(field: string, value: string): this; // ServerHeaders.add()
}

ResponseBodyWriter

interface ResponseBodyWriter {
	write(data: Uint8Array): void;
	writeString(data: string): void;
}

http-server's People

Contributors

pilcrowonpaper avatar

Stargazers

81NARY avatar Zai Chao Pan avatar HARUN OR RASHID  avatar  avatar Erik Hoffman avatar Ashish Khare avatar Chris avatar Dante Flavian Benitez avatar Teerapat Prommarak avatar SHYAKA Davis avatar Mary avatar Kyle MacDonald avatar Matvey avatar Dhi Aurrahman avatar Pablo Hdez avatar Siddharatha Nagavarapu avatar Ryan Conceicao avatar KarlitosD avatar Shoubhit Dash avatar Lucas Alves Rego avatar Saurabh Prakash avatar Stella avatar Lewin Kelly avatar akshay kadam (a2k) avatar Uzo Olisemeka avatar Ahmed Qassem avatar Diego Santos avatar Jules avatar Sefunmi avatar Marcis Bergmanis avatar Parth Kabra avatar  avatar FrancelWebdev avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.