Skip to content

Instantly share code, notes, and snippets.

@dwaps
Created December 9, 2019 15:33
Show Gist options
  • Save dwaps/00cb4b459df9c305673d5db468e2181e to your computer and use it in GitHub Desktop.
Save dwaps/00cb4b459df9c305673d5db468e2181e to your computer and use it in GitHub Desktop.
NODE: Exercice routing simple 2
<!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>
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