Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

153
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda