finished front and backend

This commit is contained in:
2025-06-10 20:29:49 +02:00
parent fb4f641197
commit 5e05db0d6e
8 changed files with 360 additions and 162 deletions

View File

@@ -1,16 +1,68 @@
const express = require("express");
const app = express();
const fs = require("fs");
const path = require("path");
app.set("view engine", "ejs");
app.get("/", (req, res) => {
res.render("index");
const recipesFolder = path.join(__dirname, "database/recipes");
fs.readdir(recipesFolder, (err, files) => {
if (err) {
return res.status(500).send("Error by reading recipe files!");
}
const txtFiles = files.filter((file) => file.endsWith(".txt"));
const recipes = txtFiles.map((file) => {
const content = fs.readFileSync(path.join(recipesFolder, file), "utf8");
return {
title: path.basename(file, ".txt"),
content: content,
};
});
res.render("index", { recipes });
});
});
app.get("/add", (req, res) => {
res.render("addRecipe/index");
});
// middleware for add recipe
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// add recipe script
app.post("/add/create-recipe", (req, res) => {
const { filename, content } = req.body;
const directory = path.join(__dirname, "database/recipes");
// left out if statement for directory check
/*
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory);
}
*/
const filePath = path.join(directory, `${filename}.txt`);
fs.writeFile(filePath, content, (err) => {
if (err) {
console.error(err);
return res
.status(500)
.console.error("Error by creating file")
.send("Error by creating file. Please check browser console!");
}
res.render("success", {
filename: filename,
path: filePath,
});
});
});
const recipeRouter = require("./routes/recipes");
app.use("/recipe", recipeRouter);