Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
Object not deleting on DELETE request

I'm new to node.js trying to delete an object from a JSON file on the DELETE request I've written this code but still, the object is not deleting from the JSON file.

const express = require('express');
const fs = require('fs');
const app = express();
app.use(express.json());
const cars = JSON.parse(fs.readFileSync(`${__dirname}/Data/cars.json`))

const deleteCar = (req, res)=>{
 const id = req.params.id * 1
 let Acar = cars.find(el => el.id === id);
 if(!Acar){
      return res.status(404).json({
           status : "failed",
           message : "request not found"
      })
 }
 fs.writeFile(`${__dirname}/Data/cars.json`, JSON.stringify(cars), err=>{
      res.status(204).json({
           status : "success",
           data : {
                car : cars.splice(Acar, 1)
           }
      })
 })
};
app.delete('/api/v1/cars/:id', deleteCar)

const port = 2000
app.listen(port, ()=>{
console.log(`listening at port ${port}`);
})
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

That is because you are not written any code to delete it from the file.

 const del_index = cars.findIndex(el => el.id === id);
 cars.splice(del_index, 1)
about 4 years ago · Juan Pablo Isaza Relatório

0

You don't appear to actually remove the item from the cars array before you write the file. It looks like you remove the item from the array inside the "err" callback, which means it will only remove it when the write fails.

I'm not sure the splice(Acar,1) if Acar is the object itself, not the index. The code below should work.


    // ...
    cars.splice(cars.indexOf(ACar, 1))
    // fs.write etc.

about 4 years ago · Juan Pablo Isaza Relatório

0

instead of using find, findIndex would help you since you are going to splice using the index, also you need to do the splicing before you save the cars to the json file

if you use 204 status code no content will be responded

const express = require('express');
const fs = require('fs');
const app = express();
app.use(express.json());
const cars = JSON.parse(fs.readFileSync(`${__dirname}/Data/cars.json`))

const deleteCar = (req, res) => {
    const id = req.params.id * 1
    let car_index = cars.findIndex(el => el.id === id);
    if (car_index === -1) {
        return res.status(404).json({
            status: "failed",
            message: "request not found"
        })
    }
    cars.splice(car_index, 1)
    fs.writeFile(`${__dirname}/Data/cars.json`, JSON.stringify(cars), err => {
        res.status(204).json(cars)
    })
};
app.delete('/api/v1/cars/:id', deleteCar)

const port = 2000
app.listen(port, () => {
    console.log(`listening at port ${port}`);
})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda