Problem when deleting item in a json file

Asked

Viewed 83 times

-2

When accessing this route that deletes an item:

app.get("/excluir/:id/:categoria", (req, res) => {
  let dados = JSON.parse(fs.readFileSync("./data/dados.json", "utf8"));

  var id = req.params.id;
  var categoria = req.params.categoria;

  console.log(id, categoria);

  for (var i = 0; i < dados.length; i++) {
    if (dados[i].id == id && dados[i].categoria) {
      delete dados[i];
    }
  }

  dados = dados.filter(function (el) {
    return el != null;
  });

  fs.writeFile("./data/dados.json", JSON.stringify(dados, null, 2), function (
    err
  ) {
    if (!err) return res.send("Write file error!");
  });

  console.log(dados);

  res.redirect("/cardapio");
});

My browser looks like this:

inserir a descrição da imagem aqui

But if I reload the tab it works perfectly.

  • Friend, remove the first image and enter the code. Then select the code and press Ctrl+K

  • This error is not related to your code, but rather that the server on localhost is not running. Happens in the same session only with this route, the others work normally?

  • I realized that the problem is in the part of the writing in the file, it is not waiting to write in the file to then run the next line, why when I update the right, because it gave time to finish the execution.

2 answers

1

Wait for the asynchronous recording of the data and only then close the request, otherwise the express won’t be able to write the headers properly.

fs.writeFile("./data/dados.json", JSON.stringify(dados, null, 2), function (
  err
) {
  // com o !err o express tentava enviar 2 respostas ao navegador..
  if (err) { return res.send("Write file error!"); }
  console.log(dados);
  res.redirect("/cardapio");
});

0

You have compared dados[i].id == id which if true will return a True, and then Voce with a boolean operator (&&) calls the dados[i].categoria and if the category is not a true that if will always give false and the code delete dados[i]; will never be executed, Now the not found page may be some error in redirecting.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.