i'm facing a problem using fs in a next.js / react app context so i'm doing a little app for renting appartments i have a json file named database.json with some datas in it and i'm able to retrieve it and use it with the Next.js Api routing where i can make my own little API. but when i try to write this file just nothing happened.
stack : React 18 / Next.js 13 / Node 18.0 via npm run dev
Here is my API File
import type { NextApiHandler } from 'next'
import apartmentList from '@/database.json'
import { actions } from '@/helpers/apiAction.js'
var fs = require('fs')
const DeleteApartmentsHandler: NextApiHandler = async (request, response) => {
const { deleteId } = request.query
const newDataSet = apartmentList.data.filter((item) => item.id !== Number(deleteId))
if (newDataSet.length === apartmentList.data.length - 1) {
const makeDelete = actions.delete(Number(deleteId))
if (makeDelete) {
response.status(200).json(`l'appartement ${deleteId} a bien été supprimé`)
} else {
response.status(501).json("Nous avons rencontré un soucis durant la suppression")
}
} else {
response.status(500).json("il semblerait qu'aucun element n'ait été supprimé")
}
}
export default DeleteApartmentsHandler
This is how i call it (this is not the final version, just working on modifying the file):
fetch(`api/delete/${id}`)
.then(res => {
console.log(res)
// push('/')
})
.catch(err => console.log(err))
then this is my helpers/apiActions.js file with the purpose to make the operations on the JSON file
// tried an ES6 import
// import fs from 'fs'
var fs = require('fs')
let apartmentList = require("../database.json")
// i tried a out of src/ file
// let apartmentListsec = require("../../database.json")
export const actions = {
delete: _delete
}
function _delete(id) {
const newDataSet = apartmentList.data.filter((item) => item.id !== id)
try {
fs.writeFileSync("../database.json", JSON.stringify(newDataSet, null, 4))
return true
} catch(err) {
console.log(err)
return false
}
}
and finally this is my data : https://file.io/pO2hVHzgIur2
i went on internet and everything, i changed the rights of my files src/, the file that make the update, the api files, etc (i won't make it online) i tried using writeFile (with async) and writeFileSync, i tried to move my files out of src/, i tried to change the TS file to JS
but none of these solutions worked.
i've tried to log my data this formatted how i want without the item i want to remove, the fs.writefilesync function that return 'undefined' i tried to use it from the api file directly or to passe via the helpers/apiActions.js, none work
so Stackoverflow is my last chance, i've spent hours on the problem i can't find what happening wrong