Created
December 9, 2019 15:33
-
-
Save dwaps/00cb4b459df9c305673d5db468e2181e to your computer and use it in GitHub Desktop.
NODE: Exercice routing simple 2
This file contains 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
<!DOCTYPE html> | |
<html lang="fr"> | |
<head> | |
<meta charset="utf-8"> | |
<title>TITLE</title> | |
<link rel="stylesheet" href="css/style.css"> | |
</head> | |
<body> | |
<h1>Bienvenue sur mon site !</h1> | |
<script src="js/app.js"></script> | |
</body> | |
</html> |
This file contains 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 { readFileSync } = require('fs'); | |
// Utils | |
const headers = new Map([ | |
['css', 'text/css'], | |
['html', 'text/html; charset=utf-8'], | |
['js', 'text/javascript'], | |
]); | |
const getFileExt = (req) => { | |
const endUrlPart = req.url.substr(req.url.lastIndexOf('.')+1); | |
return endUrlPart.includes('/') ? 'html' : endUrlPart; | |
}; | |
// Controller | |
const buildResponse = (req, res) => { | |
const fileType = getFileExt(req); | |
const filePath = (req.url === '/') | |
? 'index.html' | |
: req.url.replace('/', ''); | |
if (fileType === 'ico') { | |
res.end(); | |
return; | |
} | |
res.setHeader('Content-Type', headers.get(fileType)); | |
res.end(readFileSync(filePath)); | |
}; | |
const PORT = 5656; | |
http.createServer(buildResponse).listen(PORT); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment