klaurtar1
klaurtar1

Reputation: 788

Write a server request to file in Node

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);
  });
});

Upvotes: 0

Views: 147

Answers (1)

Mureinik
Mureinik

Reputation: 311808

If an object doesn't override the toString method (as req 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:

server.on('request', (req, res) => { 
 const jsonString = JSON.stringify(req);
 fs.writeFile('userData.json', jsonString, 'utf8', () => {
    console.log(jsonString);
  });
});

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:

const flatted = require('flatted');
server.on('request', (req, res) => { 
 const jsonString = flatted.stringify(req);
 fs.writeFile('userData.json', jsonString, 'utf8', () => {
    console.log(jsonString);
  });
});

Upvotes: 1

Related Questions