skip to Main Content

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

2

Answers


  1. 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));

    Login or Signup to reply.
  2. that error is happening because fs.writeFileSync expects the data argument to be a string, Buffer, TypedArray, or DataView.

    In your case, you’re trying to write an object (req.body) directly to the file, which is not supported.

    To fix this, convert the req.body into a JSON string with JSON.stringify() before writing it to the file. Here’s how you should do it:

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

    With this change, you should be able to write the object to the JSON file without any issues.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search