index.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. const fs = require("node:fs");
  2. const express = require("express");
  3. const app = express();
  4. const port = 7788;
  5. const data = "./data.json";
  6. app.use(express.json());
  7. app.get("/api/text", (req, res) => {
  8. fs.readFile("data.json", "utf8", (err, data) => {
  9. if (err) {
  10. res.send(err);
  11. return;
  12. }
  13. res.set("Access-Control-Allow-Origin", "*");
  14. res.send(data);
  15. });
  16. });
  17. app.post("/api/add", (req, res) => {
  18. let content = {};
  19. if (req.body) {
  20. content = req.body;
  21. } else {
  22. console.log("AAAA");
  23. res.send("ERROR: NO BODY SPECIFIED");
  24. return;
  25. }
  26. let text = content.text;
  27. fs.readFile("data.json", "utf8", (err, data) => {
  28. if (err) {
  29. res.send(err);
  30. return;
  31. }
  32. let array = JSON.parse(data)["text-array"];
  33. array.push(text);
  34. let arrjson = '{"text-array": [';
  35. for (let i in array) {
  36. if (i == array.length - 1) {
  37. arrjson += '"' + array[i] + '"';
  38. } else {
  39. arrjson += '"' + array[i] + '",';
  40. }
  41. }
  42. arrjson += "]}";
  43. fs.writeFileSync("data.json", arrjson);
  44. res.set("Access-Control-Allow-Origin", "*");
  45. //res.send(text);
  46. });
  47. });
  48. app.post("/api/remove", (req, res) => {
  49. let content = {};
  50. if (req.body) {
  51. content = req.body;
  52. } else {
  53. res.send("ERROR: NO BODY SPECIFIED");
  54. return;
  55. }
  56. let id = content.id;
  57. console.log(id);
  58. fs.readFile("data.json", "utf8", (err, data) => {
  59. if (err) {
  60. res.send(err);
  61. return;
  62. }
  63. let array = JSON.parse(data)["text-array"];
  64. array.splice(id, 1);
  65. let arrjson = '{"text-array": [';
  66. for (let i in array) {
  67. if (i == array.length - 1) {
  68. arrjson += '"' + array[i] + '"';
  69. } else {
  70. arrjson += '"' + array[i] + '",';
  71. }
  72. }
  73. arrjson += "]}";
  74. fs.writeFileSync("data.json", arrjson);
  75. });
  76. res.set("Access-Control-Allow-Origin", "*");
  77. //res.send("Removed element at id: " + id);
  78. });
  79. app.listen(port, () => {
  80. console.log(`Example app listening on port ${port}`);
  81. });