@node-server/renderer
Version:
NodeServerJs is a library with standard feature implemented for web and api
50 lines (44 loc) • 1.75 kB
text/typescript
import * as fs from "fs";
import * as path from "path";
import * as url from 'url';
import { Renderer } from "@node-server/utils";
export class RessourceRenderer extends Renderer {
DefaultFile:string;
constructor(config) {
super({
default :{
debug : false,
default_file : "index.html",
folder : "dist",
case_sensitive : false,
extentions : ["png", "ico", "svg", "jpeg", "jpg", "ott", "txt" , "js" , "css" ,"map" , "woff" , "ttf" , "json"]
},
userDefined : config
});
if(!this.pluginConfig.case_sensitive)
this.pluginConfig.extentions.map(x => typeof x === "string" ? x.toLowerCase() : x);
}
Start(app){
super.Start(app);
this.DefaultFile = this.Config.GetFolder(this.pluginConfig.folder,this.pluginConfig.default_file)
}
Condition(req, res){
var extension = path.extname(url.parse(req.url).pathname).replace(".", "");
if(this.pluginConfig.case_sensitive)
extension = extension.toLowerCase();
return this.pluginConfig.extentions.indexOf(extension) > -1;
}
Handle(req: any, res: any, next:(any) => void): void {
var file = this.Config.GetFolder(this.pluginConfig.folder,req.originalUrl);
file = url.parse(file).pathname;
if (fs.existsSync(file))
res.sendFile(file);
else {
file = this.DefaultFile;
if (fs.existsSync(file))
res.status(404).sendFile(file);
else
throw new Error("Default file not found in directory")
}
}
}