}
/**
* handler request
* @param {*} req
* @param {*} res
*/
requestHandler(req, res) {
const { pathname } = url.parse(req.url);
const filepath = path.join(this.rootPath, pathname);
// To check if a file exists
fs.stat(filepath, (err, stat) => {
if (!err) {
if (stat.isDirectory()) {
this.responseDirectory(req, res, filepath, pathname);
} else {
this.responseFile(req, res, filepath, stat);
}
} else {
this.responseNotFound(req, res);
}
});
}
/**
* Reads the contents of a directory , response files list to client
* @param {*} req
* @param {*} res
* @param {*} filepath
*/
responseDirectory(req, res, filepath, pathname) {
fs.readdir(filepath, (err, files) => {
if (!err) {
const fileList = files.map(file => {
const isDirectory = fs.statSync(filepath + '/' + file).isDirectory();
return {
filename: file,
url: path.join(pathname, file),
isDirectory
};
});
const html = handlebars.compile(templates.fileList)({ title: pathname, fileList });
res.setHeader('Content-Type', 'text/html');
res.end(html);
}
});
}
/**
* response resource
* @param {*} req
* @param {*} res
* @param {*} filepath
*/
async responseFile(req, res, filepath, stat) {
this.cacheHandler(req, res, filepath).then(
data => {
if (data === true) {
res.writeHead(304);
res.end();
} else {
res.setHeader('Content-Type', mime.getType(filepath) + ';charset=utf-8');
res.setHeader('Etag', data);
this.cors && res.setHeader('Access-Control-Allow-Origin', '*');
const compress = this.compressHandler(req, res);
if (compress) {
fs.createReadStream(filepath)
.pipe(compress)
.pipe(res);
} else {
fs.createReadStream(filepath).pipe(res);
}
}
},
error => {
this.responseError(req, res, error);
}
);
}
/**
* not found request file
* @param {*} req
* @param {*} res
*/
responseNotFound(req, res) {
const html = handlebars.compile(templates.notFound)();
res.writeHead(404, {
'Content-Type': 'text/html'
});
res.end(html);
}
/**
* server error
* @param {*} req
* @param {*} res
* @param {*} err
*/
responseError(req, res, err) {
res.writeHead(500);
res.end(`there is something wrong in th server! please try later!`);
}
/**
* To check if a file have cache
* @param {*} req
* @param {*} res
* @param {*} filepath
*/
cacheHandler(req, res, filepath) {
return new Promise((resolve, reject) => {









