0

All I want is to log my req/res object to a file(so i can refer to it later for any object values) on redirecting to a particular page.

I tried this:

app.get("/route", function(req, res) {
res.render("route");
fs.writeFile('./data.json', JSON.stringify(req, null, 2) , 'utf-8', function(err) {
    if(err) {
        return console.log(err);
    }
    console.log("The file was saved!");
});

The above code is throwing error as so:

TypeError: Converting circular structure to JSON at Object.Stringify (native)

Is there anything I should be doing differently? Any help is appreciated. Thanks in advance.

2 Answers2

0

req contains a reference to the res object, and res contains a reference back to req, so it really is a circular reference where stringify will not work.

A quick solution might be to be more choosy about which properties you want to save. For example, save req.body to file - just be picky about the data you really need.


Long term, you should consider if this is what you really want. File I/O is "expensive". You might want to put data into a database, or keep it in memory somehow.

arbuthnott
  • 3,819
  • 2
  • 8
  • 21
0

Are you need all req-object to save?

If you should save only query, try this:

app.get("/route", function(req, res) {
     res.render("route");
     fs.writeFile('./data.json', JSON.stringify(req.query, null, 2), 
    'utf-8', function(err) {
         if(err) {
              return console.log(err);
         }
    console.log("The file was saved!");
 });

if you want any additional data, firstly create new object, and assign this data to that object, and use JSON.stringify(yourObject, null, 2)

razMki
  • 91
  • 1