/
Nik054
/
fastify-master
Обзор
Документация
Войти
/
Nik054
/
fastify-master
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
app.js
72 строки
2 KB
vlad
Delete item function added.
05 ноя 2025, 20:03
05 ноя 2025, 20:03
1751e37
Код
Авторство
О чём код?
import Fastify from "fastify"; import formbody from "@fastify/formbody"; import fastifystatic from "@fastify/static"; import fastifyview from "@fastify/view"; import path, { dirname } from "path"; import { fileURLToPath } from "url"; import ejs from "ejs"; import fs from "fs"; const port = 8211; const app = Fastify ({logger: false}); app.register(formbody); app.register(fastifystatic, { root: path.join(dirname(fileURLToPath(import.meta.url)), "public"), }); app.register(fastifyview, { engine: { ejs: ejs, }, root: path.join(dirname(fileURLToPath(import.meta.url)), "views"), }) app.get('/', (req, res) => { let fileContent = fs.readFileSync("./items.json", "utf8") let data = JSON.parse(fileContent); res.view("home", {items: data}); }); app.get("/items/:id", (req, res) => { let fileContent = fs.readFileSync("./items.json", "utf8") let data = JSON.parse(fileContent); let id = req.params.id; let item = data.filter(item => item.id == id); res.view("item", {item: item[0]}); }); app.post("/items/store", (req, res) => { // console.log(req.body.id); // console.log(req.body.name); let fileContent = fs.readFileSync("./items.json", "utf8") let data = JSON.parse(fileContent); data.push({ id: req.body.id, name: req.body.name, }) fs.writeFile('./items.json', JSON.stringify(data, null, 4), () => { res.redirect('/'); }) }); app.post("/items/delete", (req, res) => { let fileContent = fs.readFileSync("./items.json", "utf8") let data = JSON.parse(fileContent); let id = req.body.id; let items = data.filter(item => item.id != id); fs.writeFile('./items.json', JSON.stringify(items, null, 4), () => { res.redirect('/'); }) }); app.listen({ host: "0.0.0.0", port: port}, () =>{ console.log(`Server is running on port ${port}`) });