Created
April 27, 2022 14:10
-
-
Save semiarthanoian/cb1cac952dca9f79ee593765a9402db6 to your computer and use it in GitHub Desktop.
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 fsPromises = require('fs/promises'); | |
const path = require('path'); | |
const handleHomeRequest = function(request, response) { | |
var indexHtml = path.join(__dirname, 'static', 'index.html'); | |
fsPromises.readFile(indexHtml) | |
.then(function(data) { | |
response.setHeader('content-type', textType.html); | |
response.writeHead(200); | |
response.end(data); | |
}) | |
.catch(function(error) { | |
console.error(error); | |
}); | |
}; // handleHomeRequest | |
const handlePostRequest = function(request, response) { | |
var postHtml = path.join(__dirname, 'static', request.url); | |
fsPromises.readFile(postHtml) | |
.then(function(data) { | |
response.setHeader('content-type', textType.html); | |
response.writeHead(200); | |
response.end(data); | |
}) | |
.catch(function(error) { | |
console.error(error); | |
handleOopsRequest(request, response); | |
}); | |
}; // handlePostRequest | |
const handleAssetRequest = function(request, response) { | |
var assetFile = path.join(__dirname, 'static', request.url); | |
fsPromises.readFile(assetFile) | |
.then(function(data) { | |
var contentType = textType.get(request.url); | |
response.setHeader('content-type', contentType); | |
response.writeHead(200); | |
response.end(data); | |
}) | |
.catch(function(error) { | |
console.error(error); | |
}); | |
}; // handleAssetRequest | |
const handleOopsRequest = function(request, response) { | |
var oopsHtml = path.join(__dirname, 'static', 'oops.html'); | |
fsPromises.readFile(oopsHtml) | |
.then(function(data) { | |
response.setHeader('content-type', textType.html); | |
response.writeHead(404); | |
response.end(data); | |
}) | |
.catch(function(error) { | |
console.error(error); | |
}); | |
}; // handleOopsRequest | |
const textType = { | |
html: 'text/html', | |
css: 'text/css', | |
js: 'text/javascript', | |
get(url) { | |
if (url.endsWith('.html')) | |
return textType.html; | |
else if (url.endsWith('.css')) | |
return textType.css; | |
else if (url.endsWith('.js')) | |
return textType.js; | |
else | |
return ''; | |
} | |
}; // textType | |
module.exports = { | |
handleHomeRequest, | |
handlePostRequest, | |
handleAssetRequest, | |
handleOopsRequest | |
}; // exports |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment