Delete Requests not persisting in node js

Viewed 78

Anytime I make a delete request to my node js server, it can only delete one item from my json file between server starts. If I try to make a second delete request, it works, but it also rewrites back the last item I deleted.

Here is the node js delete implementation using express:

const todos = require("./todos.json"); //Load the node js File
const fs = require("fs");

app.delete("/api/:id", (req, res) => {
  const id = req.params.id;
  let newTodos = todos.filter((todo) => {
    return todo.id !== id;
  });
  fs.writeFileSync(__dirname + "/todos.json", JSON.stringify(newTodos));
  todos = newTodos;
  res.send("Todo deleted");
});

This is how the items in the json file look they are contained in a regualar array:

  {
    "id": "bd58d991-bdda-4d8d-aca3-ae7ee01e1296",
    "activity": "Buy Groceries",
    "completed": false
  }
1 Answers

You should read todos.json at the beginning of delete handler.

app.delete("/api/:id", (req, res) => {
  const todos = fs.readFileSync("./todos.json", { encoding: 'utf-8' })
  ...
Related