Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/ethan-arrowood/fastify-inject-html-example

An example of injecting HTML into a static file Fastify server
https://github.com/ethan-arrowood/fastify-inject-html-example

Last synced: 9 days ago
JSON representation

An example of injecting HTML into a static file Fastify server

Awesome Lists containing this project

README

        

# Injecting HTML into a Fastify Static File Server

Recently, I've been exploring how to build a live reload server from scratch (keep an eye out for a future post on this). During this exploration, I had to figure out how to inject HTML into the payload of a [fastify](https://fastify.dev) static file server ([`@fastify/static`](https://github.com/fastify/fastify-static)) response. My solution utilizes the Node.js [Buffer](https://nodejs.org/api/buffer.html) API and a custom Node.js [Transform](https://nodejs.org/api/stream.html#class-streamtransform) stream. Let's dive in!

> [!NOTE]
>
> The source code is available here: https://github.com/Ethan-Arrowood/fastify-inject-html-example

To get started, import the necessary dependencies and instantiate the fastify server.

```js
import fastify from "fastify";
import fastifyStatic from "@fastify/static";
import path from "node:path";
import stream from "node:stream";

const server = fastify({ logger: true });

server.register(fastifyStatic, {
root: path.join(import.meta.dirname, "site"),
});

// Insert the remaining code here, before the `.listen()` call

server.listen({
port: 3000,
listenTextResolver: function listenTextResolver(address) {
return `Server listening at ${address}`;
},
});
```

Next, create some necessary constants.

```js
const ENCODED_CLOSING_HTML_TAG = new Uint8Array([
60, 47, 104, 116, 109, 108, 62,
]);

const INJECT_CODE = fs.readFileSync(
path.join(import.meta.dirname, "inject.html"),
);
```

The `ENCODED_CLOSING_HTML_TAG` is the encoded string `'