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/command.js | 8 ++++++-- src/server.js | 43 +++++++++++++++++++++++++++++++++++++++++++ src/template.html | 11 +++++++++++ 3 files changed, 60 insertions(+), 2 deletions(-) create mode 100644 src/server.js create mode 100644 src/template.html (limited to 'src') diff --git a/src/command.js b/src/command.js index c022c81..b2f7091 100644 --- a/src/command.js +++ b/src/command.js @@ -8,6 +8,7 @@ import { removeNote, } from "./notes.js"; import { listNotes } from "./utils.js"; +import { start } from "./server.js"; yargs(hideBin(process.argv)) .command( @@ -78,13 +79,16 @@ yargs(hideBin(process.argv)) type: "number", }); }, - async (argv) => {}, + async (argv) => { + const notes = await getAllNotes(); + start(notes, argv.port); + }, ) .command( "clean", "remove all notes", () => {}, - async (argv) => { + async () => { await removeAllNotes(); console.log("db reseted"); }, 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}`); +}; diff --git a/src/template.html b/src/template.html new file mode 100644 index 0000000..c8e9f47 --- /dev/null +++ b/src/template.html @@ -0,0 +1,11 @@ + + + + + + Notes + + +
{{ notes }}
+ + -- cgit v1.3