Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
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
- Host: GitHub
- URL: https://github.com/ethan-arrowood/fastify-inject-html-example
- Owner: Ethan-Arrowood
- Created: 2024-06-03T03:56:38.000Z (7 months ago)
- Default Branch: main
- Last Pushed: 2024-06-04T03:24:03.000Z (7 months ago)
- Last Synced: 2024-12-06T23:05:17.731Z (16 days ago)
- Language: JavaScript
- Size: 16.6 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
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-exampleTo 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 `'