-
Notifications
You must be signed in to change notification settings - Fork 0
/
serve-static.ts
37 lines (33 loc) · 963 Bytes
/
serve-static.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { constants, ServerHttp2Stream } from 'http2';
import * as path from 'path';
import * as mime from 'mime-types';
const {
HTTP_STATUS_NOT_FOUND,
HTTP_STATUS_INTERNAL_SERVER_ERROR,
} = constants;
function respondErrorToStream(
err: NodeJS.ErrnoException,
stream: ServerHttp2Stream,
): void {
console.log(err);
if (err.code === 'ENOENT') {
stream.respond({ ":status": HTTP_STATUS_NOT_FOUND });
}
else {
stream.respond({ ":status": HTTP_STATUS_INTERNAL_SERVER_ERROR });
}
stream.end();
}
export function serveStaticContent(
reqPath: string,
contentBase: string,
stream: ServerHttp2Stream,
): void {
const fullPath = path.join(contentBase, reqPath);
const responseMimeType = mime.lookup(fullPath);
return stream.respondWithFile(
fullPath,
{ 'content-type': responseMimeType as string },
{ onError: (err) => respondErrorToStream(err, stream) },
);
}