Created
January 26, 2020 19:58
-
-
Save LautaroJayat/16eac0bf32535aa48b8471aa28aa2ab7 to your computer and use it in GitHub Desktop.
index.js - Redirecting css and javascript calls
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 server = http.createServer((req, res) => { | |
| const URL = req.url; | |
| if (req.url === '/') { | |
| // We try to read the method in a Synchronous way | |
| // Note that we dont assign the output to a variable, | |
| // instead, we store the output in the second parameter of the | |
| // callback function. | |
| fs.readFile('./views/index.html', (err, data) => { | |
| // A little bit of error handling | |
| if (err) { | |
| res.writeHead(404); | |
| res.write('file not found'); | |
| throw err; | |
| } else { | |
| // We Write the headers | |
| res.writeHead(200, { | |
| 'Content-Length': data.length, | |
| 'Content-Type': 'text/html', | |
| }); | |
| // We send the using the second argument in the callback function | |
| console.log(data); | |
| res.write(data); | |
| res.end(); | |
| } | |
| }); | |
| } | |
| if (URL.indexOf('.css') > 0) { | |
| 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': 'text/css', | |
| }); | |
| res.write(data); | |
| res.end(); | |
| } | |
| }) | |
| } | |
| if (URL.indexOf('.js') > 0) { | |
| 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); | |
| } | |
| }) | |
| } | |
| }).listen(PORT); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment