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}`);
})

Answer

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.