res : [ Circular ] nodejs
Circular references occur when an object references itself directly or indirectly.
In Node.js, when attempting to stringify an object with circular references using
JSON.stringify()
, the default behavior is to throw aTypeError
.To handle circular references, the
JSON.stringify()
method provides a replacer function as the second argument.The replacer function is invoked for each item being stringified and can transform the object properties before serialization.
To implement a custom replacer function, it should keep track of already visited objects to avoid infinite recursion.
A common approach is to use an array to store visited objects and check whether an object has been visited before.
The replacer function can be defined to replace circular references with a placeholder value, breaking the circular structure.
Once the stringification is complete, a reviver function can be used when parsing the JSON string to restore the circular references.
The reviver function is provided as the second argument to
JSON.parse()
and can identify the placeholder values and restore the circular references accordingly.Implementing a solution for handling circular references in Node.js involves defining both a replacer function for
JSON.stringify()
and a reviver function forJSON.parse()
to ensure a proper serialization and deserialization process.