cloud-worker v0.0.3
Cloud Worker
This project is based on the ideas from the Service Worker specification and the CloudFlare Worker project.
Outline
Create a single worker file that accepts a fetch event and calls event.respondWith with a promise (such as another fetch).
The module can be used as a standalone server (possibly to test CloudFlare Workers) or as middleware in your own projects or can be invoked manually.
Installation and usage
Cloud Worker requires Node and is installed using npm (which comes with node):
npm install cloud-workerIf you want to only write a cloud worker file, then you can use the prebuilt server in your npm scripts like this:
{
"scripts": {
"start": "worker index.js"
}
}…where index.js contains your worker. For example, this cloud-worker demo waits 3 seconds then sends all request the response from a example.com (source code).
Here's some recipes of what a cloud worker can do.
Direct usage
The module can be required and used directly, and the (current) API is:
const worker = require('cloud-worker');Behind the scenes
The cloud worker uses Node's vm module to globally scope all of the required API that the service worker-like script would expect.
It waits for a single addEventListener for the fetch event and triggers that event when the worker.handler function is invoked passing in a event that contains a request object.
The functionality is provided via the following npm modules:
fetch(and related sub modules includingRequest,Response,Headers,FetchError) via node-fetchResponse.redirectis manually addedURLandURLSearchParamsvia node's internal url package- streams (
ReadableStream,WritableStreamandTransformStream) via web-streams-polyfill (though I believe this to be out of date - any user contribution would be grateful here) - encoding (
TextEncoderandTextDecoder) via text-encoding FetchEventis manually added