1

Current state of my product.json file:

{
    "product" : [
        {
            "price": 15.1,
            "amount": 6
        }
    ]
}

ideally, after writing to the file and changing the price to 20, i want the file to end up looking like this:

{
    "product" : [
        {
            "price": 20,
            "amount": 6
        }
    ]
} 
  • Can this be achieved with fs.writeFile or something similar?
  • If not, is there another way i can do what i want?

current state of my router:

router.get("/", function(req, res){
    try{
        let comms = JSON.parse(fs.readFileSync(path.resolve("server",'../product.json')))
        res.status(200).json(comms);
    } catch(err){
        res.status(500).json({
            message: "Error retrieving commission(Server)"
        });
    }
}) 

router.post("/price", function(req, res){
    try{
        var input = req.params.price
        comms.push(price);
        var data = JSON.stringify(comms);
        fs.writeFile(path.resolve("server",'../product.json'), comms, function(err){
            if (err){
                return console.log(err);
            }
            console.log("the file was saved");
        });
    } catch(err){
        res.status(500).json({
            message: "Error writing to file",
            error: err

        });
    }
})

The code above is my attempt of achieving this functionality. The GET router works and successfully reads file however my POST router is the one that is incorrect. How can i change my POST router to achieve the functionality i specified earlier on?

J Moss
  • 205
  • 1
  • 5
  • 13
  • 1
    Check this: https://stackoverflow.com/questions/10685998/how-to-update-a-value-in-a-json-file-and-save-it-through-node-js – fedeteka Apr 18 '20 at 00:53

0 Answers0