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
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));
that error is happening because
fs.writeFileSync
expects thedata
argument to be astring
,Buffer
, TypedArray, orDataView
.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:With this change, you should be able to write the object to the JSON file without any issues.