Skip to content

Commit

Permalink
Set content type header on served files
Browse files Browse the repository at this point in the history
  • Loading branch information
piranna committed Mar 26, 2021
1 parent c8e56f6 commit edfd28a
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 6 deletions.
14 changes: 13 additions & 1 deletion lib/run-uws-tracker.ts
Expand Up @@ -17,7 +17,9 @@

import { readFileSync } from "fs";
import { HttpResponse, HttpRequest } from "uWebSockets.js";
import { extname } from "path";
import * as Debug from "debug";
import { contentType } from "mime-types";
import { UWebSocketsTracker } from "./uws-tracker";
import { FastTracker } from "./fast-tracker";
import { Tracker } from "./tracker";
Expand Down Expand Up @@ -203,6 +205,7 @@ function buildServer(
const status = "404 Not Found";
response.writeStatus(status).end(status);
} else {
response.writeHeader("Content-Type", "text/html; charset=utf-8");
response.end(indexHtml);
}
},
Expand Down Expand Up @@ -240,10 +243,12 @@ function buildServer(
(response: HttpResponse, request: HttpRequest) => {
debugRequest(server, request);

const path = request.getUrl();

let data = undefined;

try {
data = readFileSync(`${process.cwd()}${request.getUrl()}`);
data = readFileSync(`${process.cwd()}${path}`);
} catch (err) {
console.warn(err);
}
Expand All @@ -252,6 +257,13 @@ function buildServer(
const status = "404 Not Found";
response.writeStatus(status).end(status);
} else {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
const type = contentType(extname(path)) as string | false;

if (type !== false) {
response.writeHeader("Content-Type", type);
}

response.end(data);
}
},
Expand Down
20 changes: 15 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Expand Up @@ -45,11 +45,13 @@
},
"dependencies": {
"debug": "^4.1.1",
"mime-types": "^2.1.29",
"uWebSockets.js": "github:uNetworking/uWebSockets.js#v17.4.0"
},
"devDependencies": {
"@types/chai": "^4.2.11",
"@types/debug": "^4.1.5",
"@types/mime-types": "^2.1.0",
"@types/mocha": "^7.0.2",
"@types/node": "^13.13.4",
"@types/ws": "^7.2.4",
Expand Down

0 comments on commit edfd28a

Please sign in to comment.