• Stars
    star
    325
  • Rank 129,350 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 6 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

The tiny HTTP server that gets out of your way! ・
polkadot

Polkadot

The tiny HTTP server that gets out of your way~!

Features

  • Intentionally Minimal
    Build your own stack! Polkadot doesn't even include a router.
    Polkadot can accommodate any & all of your preferences. This is your app.

  • Extremely Lightweight
    Even with all dependencies, Polkadot weighs less than 15kB!
    It's the perfect candidate for serverless environments.

  • Simple yet Flexible
    You can learn the "framework" during lunch and deploy before the day's end.
    There's no limit to what you can do – nor how you can do it.

  • Highly Performant
    Because Polkadot does so little, it's as "blazing fast" as they come.

  • Async Support
    It's the 2020s – time to await all the things~!

Install

$ npm install --save polkadot

Usage: CLI

Just specify an entry file – that's it! πŸŽ‰
If you do not provide one, then index.js is assumed.

Customize the port by setting the PORT environment variable.
The PORT will default to 3000 if left undeclared.

Important: An error will be thrown if the PORT is in use.

# Examples:

$ polkadot
$ polkadot app.js
$ PORT=8080 polkadot app.js
// index.js
const { get } = require('httpie');

module.exports = async (req, res) => {
  let uri = `https://jsonplaceholder.typicode.com/posts`;
  if (req.query.id) {
    uri += `/${req.query.id}`;
  }
  let res = await get(uri);
  return res.data;
}

Usage: Programmatic

For those who need to control the lifecycle and/or lifespan of their server(s), a programmatic API is available.
Similarly, this is the only way to customize the underlying server itself (see the with-https example).

const { get } = require('httpie');
const polkadot = require('polkadot');

const app = polkadot(async (req, res) => {
  let uri = `https://jsonplaceholder.typicode.com/posts`;
  if (req.query.id) {
    uri += `/${req.query.id}`;
  }
  let res = await get(uri);
  return res.data;
});

app.listen(3000, err => {
  if (err) throw err;
  console.log('> Running on localhost:3000');
});

API

Note: The following pertains to Programmatic Usage only

polkadot.handler(req, res)

Returns: Function

The main polkadot handler.

It parses the req (see IncomingMessage) and assigns value to the path, query, and search keys1.
It also waits until the res (see ServerResponse) has been terminated or until data is returned.2

1 See @polka/url for further details.
2 See Handlers for varying return types.

polkadot.listen()

Returns: http.Server

Boots (or creates) the underlying http.Server for the first time.
All arguments are passed directly to server.listen with no changes.

Handlers

Every handler receives a req (IncomingMessage) and a res (ServerResponse) pair of arguments.
These are the true, mostly unfettered1 instances that the http.Server created, so you have full access to all native APIs.

1 Before calling your handler(s), @polka/url assigns value to req.path, req.query, and req.search keys.

There are multiple ways to format or return the server response. You may mix and match them, as you are not restricted to a particular format in your application(s).

1. Use Native APIs

Because you have direct access to res (see ServerResponse), you can set headers, the statusCode, and/or write response data with the core Node.js methods:

module.exports = function (req, res) {
  res.statusCode = 400;
  res.setHeader('Content-Type', 'application/json');
  res.end('{"error":"Bad Request"}');
}

2. The @polka/send-type library

The @polka/send-type library is a utility function that composes your response through a simple API. It also inspects your response data and will auto-set its Content-Type (if unspecified) and Content-Length headers for you. Additionally, it will stringify Objects into JSON on your behalf!

Note: Check out its Data Detections documentation.

Because the @polka/send-type library is already a dependency of polkadot, using it comes at no extra cost!

const send = require('@polka/send-type');

module.exports = function (req, res) {
  send(res, 400, {
    error: 'Bad Request'
  });
}

3. Return data

Polka uses the @polka/send-type library internally, which allows you to return data directly from your function handler instead of using the native APIs to format the response manually.

Because of this, @polka/send-type can inspect your outgoing data and determine its Content-Type (if unspecified) and Content-Length response headers on your behalf. Similarly, it will automatically convert Objects into JSON strings.

Note: Check out its Data Detections documentation.

module.exports = function (req, res) {
  res.statusCode = 400;
  return {
    error: 'Bad Request'
  };
};

4. Async Returns

Polkadot works great with asynchronous functions!
You can certainly fetch data from external APIs, interact with databases, ...etc without any problems.

Of course, your asynchronous chain(s) may also use native res APIs, the @polka/send-type helper, or may return data directly. All options are always available!

The only rule is that if your handler ends in a Promise or AsyncFunction, that function must be returned so that Polkadot can resolve it on your behalf.

Important: The use of AsyncFunction is only supported in Node versions 7.4 and above.

// For demo, not required
const send = require('@polka/send-type');

// Using Promises
module.exports = function (req, res) {
  // must `return` the Promise
  return isUser(req).then(user => {
    if (user) {
      send(res, 200, { user });
    } else {
      send(res, 401, 'You must be logged in');
    }
  });
};

// Using AsyncFunctions
module.exports = async function (req, res) {
  const user = await isUser(req);
  if (user) {
    send(res, 200, { user });
  } else {
    send(res, 401, 'You must be logged in');
  }
}

Routing

Before your handler is called, Polkadot will parse the request to provide you with some core information.
It will use @polka/url to make req.path, req.search, and req.query available.

While polkadot does not include a router, you can create your own or import any router of your choosing!
Please check out the with-router example that uses Trouter to build a full JSON resource.

Below is a simple example that serves images & video files based on the incoming path:

const fs = require('fs');
const { join } = require('path');
const mime = require('mime/lite');

const assets = join(__dirname, 'assets');

function sendfile(res, dir, filename) {
  const file = join(assets, dir, filename);
  if (fs.existsSync(file)) {
    res.setHeader('Content-Type', mime.getType(file));
    fs.createReadStream(file).pipe(res);
  } else {
    res.statusCode = 404;
    res.end('File not found');
  }
}

// Supports: /images?filename=foobar.jpg
// Supports: /videos?filename=foobar.mp4
module.exports = function (req, res) {
  const { filename } = req.query;
  if (req.path === '/images') {
    sendfile(res, 'images', filename);
  } else if (req.path === '/videos') {
    sendfile(res, 'videos', filename);
  } else {
    res.statusCode = 404;
    res.end('Unknown filetype');
  }
}

Error Handling

You must handle your own errors. This is because Polkadot will not dictate your application design nor its behavior – and how an application responds to and handles errors is a large, important part of its design!

Please visit the with-middleware or the with-router examples.
They are both more complex demonstrations that handle errors while chaining or composing functions together.

For simple endpoints, it's very straightforward (as it should be):

// Send 404 if unknown path
module.exports = function (req, res) {
  if (req.path !== '/') {
    res.statusCode = 404;
    return 'Page not found';
  }
  return 'OK';
}

// ---

const { get } = require('httpie');

// Send 404 if ID unknown to external API
module.exports = async function (req, res) {
  try {
    const ID = req.query.id;
    let { data } = await get(`https://example.com/users/${ID}`);
    send(res, 200, { user:data });
  } catch (err) {
    const code = err.statusCode || 404;
    const message = err.data || 'User not found';
    console.error('Error: ', req.query.id, code, message);
    send(res, code, message);
  }
}

Benchmarks

For performance results and comparisons, please check out the bench directory.

Prior Art

Polkadot is the "little sibling" to Polka. It's effectively the core of Polka, stripped of all routing, middleware sequencing, and Express compatibility layers. While Polka is already leaner than most everything else, there was an opportunity to further satisfy the minimalists and make a microscopic version of Polka – hence, polkaβ€’dot.

Additionally, Polkadot follows in the footsteps of micro, which was the first HTTP framework of our kind (to my knowledge).

License

MIT Β© Luke Edwards

More Repositories

1

clsx

A tiny (239B) utility for constructing `className` strings conditionally.
JavaScript
8,212
star
2

polka

A micro web server so fast, it'll make you dance! πŸ‘―
JavaScript
5,266
star
3

pwa

(WIP) Universal PWA Builder
JavaScript
3,127
star
4

uvu

uvu is an extremely fast and lightweight test runner for Node.js and the browser
JavaScript
2,970
star
5

taskr

A fast, concurrency-focused task automation tool.
JavaScript
2,528
star
6

sockette

The cutest little WebSocket wrapper! 🧦
JavaScript
2,398
star
7

worktop

The next generation web framework for Cloudflare Workers
TypeScript
1,652
star
8

kleur

The fastest Node.js library for formatting terminal text with ANSI colors~!
JavaScript
1,616
star
9

klona

A tiny (240B to 501B) and fast utility to "deep clone" Objects, Arrays, Dates, RegExps, and more!
JavaScript
1,602
star
10

dequal

A tiny (304B to 489B) utility to check for deep equality
JavaScript
1,365
star
11

tsm

TypeScript Module Loader
TypeScript
1,179
star
12

tinydate

A tiny (349B) reusable date formatter. Extremely fast!
JavaScript
1,060
star
13

sirv

An optimized middleware & CLI application for serving static files~!
JavaScript
1,059
star
14

sade

Smooth (CLI) Operator 🎢
JavaScript
1,009
star
15

rosetta

A general purpose internationalization library in 292 bytes
JavaScript
788
star
16

navaid

A navigation aid (aka, router) for the browser in 850 bytes~!
JavaScript
775
star
17

dset

A tiny (194B) utility for safely writing deep Object values~!
JavaScript
754
star
18

tschema

A tiny (500b) utility to build JSON schema types.
TypeScript
697
star
19

uid

A tiny (130B to 205B) and fast utility to generate random IDs of fixed length
JavaScript
652
star
20

httpie

A Node.js HTTP client as easy as pie! πŸ₯§
JavaScript
579
star
21

ganalytics

A tiny (312B) client-side module for tracking with Google Analytics
JavaScript
575
star
22

regexparam

A tiny (394B) utility that converts route patterns into RegExp. Limited alternative to `path-to-regexp` πŸ™‡β€β™‚οΈ
JavaScript
565
star
23

trouter

🐟 A fast, small-but-mighty, familiar fish...errr, router*
JavaScript
563
star
24

dimport

Run ES Module syntax (`import`, `import()`, and `export`) in any browser – even IE!
JavaScript
548
star
25

mri

Quickly scan for CLI flags and arguments
JavaScript
533
star
26

tempura

A light, crispy, and delicious template engine 🍀
JavaScript
527
star
27

calendarize

A tiny (202B) utility to generate calendar views.
JavaScript
478
star
28

formee

A tiny (532B) library for handling <form> elements.
JavaScript
441
star
29

qss

A tiny (294b) browser utility for encoding & decoding a querystring.
JavaScript
408
star
30

uuid

A tiny (~230B)and fast UUID (V4) generator for Node and the browser
JavaScript
396
star
31

preact-starter

Webpack3 boilerplate for building SPA / PWA / offline front-end apps with Preact
JavaScript
387
star
32

fetch-event-stream

A tiny (736b) utility for Server Sent Event (SSE) streaming via `fetch` and Web Streams API
TypeScript
374
star
33

vegemite

A Pub/Sub state manager you'll love... or hate
JavaScript
373
star
34

resolve.exports

A tiny (952b), correct, general-purpose, and configurable `"exports"` and `"imports"` resolver without file-system reliance
TypeScript
366
star
35

matchit

Quickly parse & match URLs
JavaScript
321
star
36

flru

A tiny (215B) and fast Least Recently Used (LRU) cache
JavaScript
313
star
37

mrmime

A tiny (2.8kB) and fast utility for getting a MIME type from an extension or filename
TypeScript
312
star
38

watchlist

Recursively watch a list of directories & run a command on any file system changes
JavaScript
262
star
39

ley

(WIP) Driver-agnostic database migrations
JavaScript
261
star
40

arr

A collection of tiny, highly performant Array.prototype alternatives
JavaScript
255
star
41

flattie

A tiny (203B) and fast utility to flatten an object with customizable glue
JavaScript
254
star
42

webpack-messages

Beautifully format Webpack messages throughout your bundle lifecycle(s)!
JavaScript
246
star
43

obj-str

A tiny (96B) library for serializing Object values to Strings.
JavaScript
225
star
44

templite

Lightweight templating in 150 bytes
JavaScript
224
star
45

empathic

A set of small Node.js utilities to understand your pathing needs.
TypeScript
221
star
46

ms

A tiny (414B) and fast utility to convert milliseconds to and from strings.
JavaScript
215
star
47

nestie

A tiny (215B) and fast utility to expand a flattened object
JavaScript
201
star
48

throttles

A tiny (139B to 204B) utility to regulate the execution rate of your functions
JavaScript
199
star
49

hexoid

A tiny (190B) and extremely fast utility to generate random IDs of fixed length
JavaScript
193
star
50

astray

Walk an AST without being led astray
JavaScript
184
star
51

fromnow

A tiny (339B) utility for human-readable time differences between now and past or future dates.
JavaScript
178
star
52

tmp-cache

A least-recently-used cache in 35 lines of code~!
JavaScript
177
star
53

bundt

A simple bundler for your delicious modules
JavaScript
169
star
54

wrr

A tiny (148B) weighted round robin utility
JavaScript
164
star
55

freshie

(WIP) A fresh take on building universal applications with support for pluggable frontends and backends.
TypeScript
155
star
56

svelte-ssr-worker

A quick demo for rendering Svelte server-side (SSR), but within a Cloudflare Worker!
JavaScript
154
star
57

totalist

A tiny (195B to 224B) utility to recursively list all (total) files in a directory
JavaScript
152
star
58

escalade

A tiny (183B to 210B) and fast utility to ascend parent directories
JavaScript
148
star
59

typescript-module

Template repository for authoring npm modules via TypeScript
TypeScript
143
star
60

sublet

Reactive leases for data subscriptions
JavaScript
140
star
61

webpack-route-manifest

Generate an asset manifest file, keyed by route patterns!
JavaScript
127
star
62

semiver

A tiny (153B) utility to compare semver strings.
JavaScript
123
star
63

url-shim

A 1.5kB browser polyfill for the Node.js `URL` and `URLSearchParams` classes.
JavaScript
123
star
64

svelte-demo

Multi-page demo built Svelte 3.x and Rollup with code-splitting
Svelte
114
star
65

saturated

A tiny (203B) utility to enqueue items for batch processing and/or satisfying rate limits.
JavaScript
112
star
66

webpack-format-messages

Beautiful formatting for Webpack messages; ported from Create React App!
JavaScript
111
star
67

gittar

🎸 Download and/or Extract git repositories (GitHub, GitLab, BitBucket). Cross-platform and Offline-first!
JavaScript
111
star
68

cfw

(WIP) A build and deploy utility for Cloudflare Workers.
TypeScript
109
star
69

webpack-critical

Extracts & inlines Critical CSS with Wepack
JavaScript
109
star
70

pages-fullstack

Demo SvelteKit application running on Cloudflare Pages
Svelte
101
star
71

sort-isostring

A tiny (110B) and fast utility to sort ISO 8601 Date strings
JavaScript
98
star
72

colors-app

🎨 A PWA for copying values from popular color palettes. Supports HEX, RGB, and HSL formats.
JavaScript
95
star
73

salteen

A snappy and lightweight (259B) utility to encrypt and decrypt values with salt.
JavaScript
95
star
74

is-offline

A tiny (174B) library to detect `offline` status & respond to changes in the browser.
JavaScript
91
star
75

seolint

(WIP) A robust and configurable SEO linter
TypeScript
87
star
76

rafps

A tiny (178B) helper for playing, pausing, and setting `requestAnimationFrame` frame rates
JavaScript
82
star
77

preact-cli-ssr

A quick demo for adding SSR to a Preact CLI app
JavaScript
79
star
78

webpack-modules

Handle `.mjs` files correctly within webpack
JavaScript
71
star
79

csprng

A tiny (~90B) isomorphic wrapper for `crypto.randomBytes` in Node.js and browsers.
JavaScript
68
star
80

premove

A tiny (201B to 247B) utility to remove items recursively
JavaScript
66
star
81

classico

A tiny (255B) shim when Element.classList cannot be used~!
JavaScript
62
star
82

mk-dirs

A tiny (381B to 419B) utility to make a directory and its parents, recursively
JavaScript
54
star
83

primeval

A tiny (128B) utility to check if a value is a prime number
JavaScript
52
star
84

loadr

Quickly attach multiple ESM Loaders and/or Require Hooks together but without the repetitive `--experimental-loader` and/or `--require` Node flags
JavaScript
49
star
85

preact-progress

Simple and lightweight (~590 bytes gzip) progress bar component for Preact
JavaScript
49
star
86

route-manifest

A tiny (412B) runtime to retrieve the correct entry from a Route Manifest file.
JavaScript
46
star
87

svelte-preprocess-esbuild

A Svelte Preprocessor to compile TypeScript via esbuild!
TypeScript
45
star
88

rollup-route-manifest

A Rollup plugin to generate an asset manifest, keyed by route patterns ("route manifest")
JavaScript
41
star
89

preact-scroll-header

A (800b gzip) header that will show/hide while scrolling for Preact
JavaScript
41
star
90

inferno-starter

Webpack2 boilerplate for building SPA / PWA / offline front-end apps with Inferno.js
JavaScript
41
star
91

onloaded

A tiny (350B) library to detect when images have loaded.
JavaScript
38
star
92

route-sort

A tiny (200B) utility to sort route patterns by specificity
JavaScript
36
star
93

webpack-plugin-replace

Replace content while bundling.
JavaScript
36
star
94

scorta

A tiny (330B to 357B) and fast utility to find a package's hidden supply / cache directory.
JavaScript
34
star
95

local-hostname

A tiny (171B) utility to check if a hostname is local
JavaScript
32
star
96

taskr-outdated

A generator & coroutine-based task runner. Fasten your seatbelt. πŸš€
JavaScript
32
star
97

rewrite-imports

Rewrite `import` statements as `require()`s; via RegExp
JavaScript
31
star
98

preact-offline

A (300b gzip) component to render alerts/messages when offline.
JavaScript
29
star
99

fly-kit-preact

A starter kit for building offline / SPA / PWA apps with Preact
JavaScript
28
star
100

fannypack

The tool belt for front-end developers
JavaScript
28
star