I am curious how I could write a server request in my node application to a JSON file.
So far I have a simple event listener for my server that writes the data to a file but every time I read the file it simply says [object object]
. What am I doing wrong?
server.on('request', (req, res) => {
fs.writeFile('userData.json', req, 'utf8', () => {
console.log(req);
});
});
If an object doesn't override the
toString
method (asreq
doesn't), you'll get[Object object]
when treating it in a string context (e.g., writing it to a file). One approach to solve this is to explicitly convert the object to JSON:EDIT:
To address the issue in the comment,
JSON.stringify
doesn't handle circular references properly. You could use a 3rd party like flatted instead: