From 03bcfd27568334f7ff2b2650f5348ff43c4e19b1 Mon Sep 17 00:00:00 2001 From: hugo gogo Date: Sun, 9 Oct 2022 15:04:09 +0200 Subject: [PATCH] mini server improved --- notes_hugo.md | 1 + tests/tests_hugo/server.js | 25 ++++++++++++++++++------- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/notes_hugo.md b/notes_hugo.md index 5ff9a0e6..ddd1cc40 100644 --- a/notes_hugo.md +++ b/notes_hugo.md @@ -21,4 +21,5 @@ fs.readFile('MyFile.txt', (err, content) => { }); ``` - [doc technos generic](https://devdocs.io/) +- [url.parse deprecated](https://stackoverflow.com/questions/17184791/node-js-url-parse-and-pathname-property) diff --git a/tests/tests_hugo/server.js b/tests/tests_hugo/server.js index b6a59dd7..8f3fcb4c 100644 --- a/tests/tests_hugo/server.js +++ b/tests/tests_hugo/server.js @@ -1,19 +1,24 @@ + //const https = require('node:https') const http = require('http') const fs = require('fs') const url = require('url') -let server = http.createServer((request, response) => { - let rUrl = request.url - console.log(url.parse(rUrl)) - // read file - fs.readFile('index.html', (err, data) => { - // if reading failed return error +const rootName = (name) => { + fullName = __dirname + name + return fullName +} + +const sendHtml = (pathName, response) => { + + console.log(` name: ${pathName}`) + console.log(`namePath: ${rootName(pathName)}`) + + fs.readFile(rootName(pathName), (err, data) => { if (err) { response.writeHead(404) response.end('file not found') } - // otherwise return file content else { response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' @@ -21,7 +26,13 @@ let server = http.createServer((request, response) => { 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')