mini server improved

This commit is contained in:
hugo gogo
2022-10-09 15:04:09 +02:00
parent d15029a4db
commit 03bcfd2756
2 changed files with 19 additions and 7 deletions

View File

@@ -21,4 +21,5 @@ fs.readFile('MyFile.txt', (err, content) => {
}); });
``` ```
- [doc technos generic](https://devdocs.io/) - [doc technos generic](https://devdocs.io/)
- [url.parse deprecated](https://stackoverflow.com/questions/17184791/node-js-url-parse-and-pathname-property)

View File

@@ -1,19 +1,24 @@
//const https = require('node:https') //const https = require('node:https')
const http = require('http') const http = require('http')
const fs = require('fs') const fs = require('fs')
const url = require('url') const url = require('url')
let server = http.createServer((request, response) => { const rootName = (name) => {
let rUrl = request.url fullName = __dirname + name
console.log(url.parse(rUrl)) return fullName
// read file }
fs.readFile('index.html', (err, data) => {
// if reading failed return error const sendHtml = (pathName, response) => {
console.log(` name: ${pathName}`)
console.log(`namePath: ${rootName(pathName)}`)
fs.readFile(rootName(pathName), (err, data) => {
if (err) { if (err) {
response.writeHead(404) response.writeHead(404)
response.end('file not found') response.end('file not found')
} }
// otherwise return file content
else { else {
response.writeHead(200, { response.writeHead(200, {
'content-type': 'text/html; charset=utf-8' 'content-type': 'text/html; charset=utf-8'
@@ -21,7 +26,13 @@ let server = http.createServer((request, response) => {
response.end(data) response.end(data)
} }
}) })
}
const server = http.createServer((request, response) => {
let pathName = url.parse(request.url).pathname
// read file
if (pathName.endsWith(".html"))
sendHtml(pathName, response)
}) })
server.listen('8080') server.listen('8080')