Files
42_INT_14_transcendence/tests_hugo/pure_node/myExpress.js

66 lines
1.4 KiB
JavaScript

const http = require('http')
const fs = require('fs')
const url = require('url')
var res = http.ServerResponse.prototype
res.sendFile = function (file) {
fs.readFile(file, (err, data) => {
if (!err) {
console.log("here")
this.writeHead(200, {
'content-type': 'text/html; charset=utf-8'
})
this.end(data)
}
else
{
this.writeHead(404)
this.end('file not found')
}
})
}
class myServer {
constructor() {
this._gets = {};
this._posts = {};
this._puts = {};
this._deletes = {};
this._server = http.createServer((req, res) => {
const pathName = url.parse(req.url).pathname;
if (req.method === "GET" && this._gets[pathName]) {
this._gets[pathName](req, res);
}
else if (req.method === "POST" && this._posts[pathName]) {
this._posts[pathName](req, res);
}
else if (req.method === "PUT" && this._puts[pathName]) {
this._puts[pathName](req, res);
}
else if (req.method === "DELETE" && this._deletes[pathName]) {
this._deletes[pathName](req, res);
} else {
res.writeHead(404)
res.end('not found');
}
})
}
get(url, callback) { this._gets[url] = callback; }
post(url, callback) { this._posts[url] = callback; }
add(url, callback) { this._puts[url] = callback; }
delete(url, callback) { this._deletes[url] = callback; }
listen(port, callback) { this._server.listen(port, callback) }
}
const myExpress = () => { return new myServer() }
module.exports = myExpress;