62 lines
1.5 KiB
TypeScript

import { existsSync, readFileSync } from 'node:fs';
import { www_folder, index_alias } from './Webserver';
class Mapping {
ending: string;
encoding: string;
}
const mappings: Mapping[] = [
{ ending: 'html', encoding: 'text/html' },
{ ending: 'js', encoding: 'text/javascript' },
{ ending: 'css', encoding: 'text/css' },
{ ending: 'json', encoding: 'application/json' },
{ ending: 'ico', encoding: 'image/x-icon' },
{ ending: 'svg', encoding: 'image/svg+xml' },
{ ending: 'txt', encoding: 'text/plain' },
]
export class File {
type: string;
content: Buffer;
constructor(type: string, content: Buffer) {
this.content = content;
this.type = type;
}
}
export function file_allowed(url: string): boolean {
let allowed: boolean = false;
let m = url.match('\\.\\.');
if (m == null) {
allowed = true;
}
return allowed;
}
export function file_exists(url: string): boolean {
if(url == '/') {
url = index_alias;
}
return existsSync(www_folder + url);
}
export function file_get(url: string): File {
if(url == '/') {
url = index_alias;
}
return new File(get_type(url), readFileSync(www_folder + url));
}
function get_type(url: string): string {
if(url == '/') {
url = index_alias;
}
let type: string = 'application/octet-stream';
let m: Mapping = mappings.find((e) => e.ending == url.split('.').pop());
if(m != undefined) {
type = m.encoding;
}
return type;
}