From 51cead8d816d16cc025e4a189040bca7c0dc3729 Mon Sep 17 00:00:00 2001 From: Leo Goetz Date: Mon, 10 Nov 2025 10:26:15 +0100 Subject: completed course --- src/server.js | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/server.js (limited to 'src/server.js') diff --git a/src/server.js b/src/server.js new file mode 100644 index 0000000..eff1e38 --- /dev/null +++ b/src/server.js @@ -0,0 +1,43 @@ +import fs from "node:fs/promises"; +import http from "node:http"; +import open from "open"; + +const interpolate = (html, data) => { + return html.replace(/\{\{\s*(\w+)\s*\}\}/g, (match, placeholder) => { + return data[placeholder] || ""; + }); +}; + +const formatNotes = (notes) => { + return notes + .map((note) => { + return ` +
+

${note.content}

+
+ ${note.tags.map((tag) => `${tag}`).join("")} +
+
+ `; + }) + .join("\n"); +}; + +const createServer = (notes) => { + return http.createServer(async (_, res) => { + const HTML_PATH = new URL("./template.html", import.meta.url).pathname; + const template = await fs.readFile(HTML_PATH, "utf-8"); + const html = interpolate(template, { notes: formatNotes(notes) }); + + res.writeHead(200, { "content-type": "text/html" }); + res.end(html); + }); +}; + +export const start = (notes, port) => { + const server = createServer(notes); + server.listen(port, () => { + console.log(`Server ist listening on port ${port}`); + }); + open(`http://localhost:${port}`); +}; -- cgit v1.3