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