1

I'm trying to write an object to a JSON, when passing the data through to the server I keep receiving this error and I cannot seem to find a solution to fix it...

Here is my code

APP.post('/api', (req, res) => {
    
    const data = req.body;
    console.log(data);

    try {
        fs.writeFileSync(PATH, data);
    } catch(err) {
        console.log(err)
    }

    res.send("Updated");
});

The object looks like the following i.e. req.body

{
  name: '',
  currentStats: {
    stat: 0,

  },
  trackStats: { history: 0 }
}

The error in question

TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received an instance of Object

Cameron Shearer
  • 142
  • 1
  • 10

1 Answers1

2

fs.writeFileSync writes data in binary format, and it expects a buffer or a string as the second argument. Thus you need to convert your JavaScript object to a JSON string using JSON.stringify()

fs.writeFileSync(PATH,JSON.stringify(data));

oluroyleseyler
  • 802
  • 2
  • 5