Created
January 26, 2020 20:52
-
-
Save LautaroJayat/a7c7f89a71e0250789d6514edf8691bf to your computer and use it in GitHub Desktop.
Controllers.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const http = require('http'); | |
| const fs = require('fs'); | |
| const ctrl = {}; | |
| ctrl.forInvalidMethod = function (req, res) { | |
| res.statusCode = 405; | |
| res.setHeader('Allow', 'GET'); | |
| return res.end(); | |
| } | |
| ctrl.forIndex = function (req, res) { | |
| fs.readFile('./views/index.html', (err, data) => { | |
| if (err) { | |
| res.writeHead(404); | |
| res.write('file not found'); | |
| throw err; | |
| } else { | |
| res.writeHead(200, { | |
| 'Content-Length': data.length, | |
| 'Content-Type': 'text/html', | |
| }); | |
| res.end(data); | |
| } | |
| }) | |
| } | |
| ctrl.forJavascript = function (req, res) { | |
| fs.readFile('./public/buttons.js', (err, data) => { | |
| if (err) { | |
| res.writeHead(404); | |
| res.write('file not found'); | |
| throw err; | |
| } else { | |
| res.writeHead(200, { | |
| 'Content-Length': data.length, | |
| 'Content-Type': 'text/javascript', | |
| }); | |
| res.end(data); | |
| } | |
| }) | |
| } | |
| ctrl.forCSS = function (req, res) { | |
| let ext = req.url.split('.')[1]; | |
| let file = (function () { | |
| let splitted = req.url.split('/'); | |
| return splitted[splitted.length - 1]; | |
| })() | |
| fs.readFile('public/' + file, (err, data) => { | |
| if (err) { | |
| res.writeHead(404) | |
| res.end(); | |
| throw err | |
| } else { | |
| res.writeHead(200, { | |
| 'Concent-Length': data.length, | |
| 'Content-Type': mimeNames['.' + ext], | |
| }); | |
| res.write(data); | |
| res.end(); | |
| } | |
| }) | |
| } | |
| var mimeNames = { | |
| '.css': 'text/css', | |
| '.html': 'text/html', | |
| '.js': 'application/javascript', | |
| '.mp3': 'audio/mpeg', | |
| '.mp4': 'video/mp4', | |
| '.ogg': 'application/ogg', | |
| '.ogv': 'video/ogg', | |
| '.oga': 'audio/ogg', | |
| '.txt': 'text/plain', | |
| '.wav': 'audio/x-wav', | |
| '.webm': 'video/webm' | |
| }; | |
| module.exports = ctrl; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment