Skip to content

Commit 9d99c2b

Browse files
committed
feat: add support for fallback file
1 parent 1df4012 commit 9d99c2b

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

README.md

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
# file-domain-server
22

3-
**file-domain-server** is a simplistic Nodejs HTTP file server that serve
3+
**file-domain-server** is a simplistic Nodejs HTTP file server that serves
44
different folders depending on the HTTP `Host` header. It is mainly intended to
5-
run an internal network with its own DNS server.
5+
run on an internal network with its own DNS server.
66

77
## Get started
88

@@ -52,6 +52,10 @@ The following can be configured as environment variables:
5252

5353
- **DEFAULT_INDEX_FILE** name of file served on paths ending with a trailing
5454
slash (default `index.html`).
55+
- **FALLBACK_FILE** name of file served as a fallback if requested file is not
56+
found. Set to `index.html` to enable client-side routing or to e.g.
57+
`error.html` to display an error page (note that response still returns a 200
58+
status code). It is undefined by default and no fallback file will be served.
5559
- **PORT** the port the server should listen on (default 8080).
5660
- **ROOT_FILE_PATH** root directory of served file tree (default `build`).
5761

src/index.js

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ const mime = require("mime");
44
const path = require("path");
55

66
const DEFAULT_INDEX_FILE = process.env.DEFAULT_INDEX_FILE || "index.html";
7+
const FALLBACK_FILE = process.env.FALLBACK_FILE || null;
78
const PORT = process.env.PORT || 8080;
89
const ROOT_FILE_PATH = process.env.ROOT_FILE_PATH || "build";
910

@@ -45,7 +46,14 @@ function handleRequest(req, res) {
4546
console.debug("Requesting", domain, filePath);
4647

4748
const actualFilePath = createFilePath(domain, filePath);
48-
const file = getFile(actualFilePath);
49+
let file = getFile(actualFilePath);
50+
51+
if (!file && FALLBACK_FILE) {
52+
const fallbackFilePath = createFilePath(domain, FALLBACK_FILE);
53+
console.debug("Serving fallback file:", fallbackFilePath);
54+
file = getFile(fallbackFilePath);
55+
}
56+
4957
if (!file) {
5058
res.writeHead(404);
5159
res.end();
@@ -62,4 +70,4 @@ function handleRequest(req, res) {
6270
const server = http.createServer(handleRequest);
6371
server.listen(PORT);
6472

65-
console.info(`Listening on port ${PORT}`)
73+
console.info(`Listening on port ${PORT}`);

0 commit comments

Comments
 (0)