Node.jsの組み込みモジュールutilを使ってオブジェクトを文字列に変換する(循環参照編)

前に書いた記事の補足、追加で調べた内容です。

s1r-j.hatenablog.com

utilモジュールを使って文字列化する場合、オブジェクトのプロパティが自分自身を参照していると[Circular *1]に変換されると書きました。

自分自身を参照しているオブジェクトは、下のmyselfのように出力されます。

<ref *1> { depth1: { depth2: { depth3: { depth4: { depth5: { depth6: 'deep' } } } } }, string: 'this is string', longString: "I thought what I'd do was, I'd pretend I was one of those deaf-mutes. I thought what I'd do was, I'd pretend I was one of those deaf-mutes. I thought what I'd do was, I'd pretend I was one of those deaf-mutes.", number: 123456, array: [ 1, 2, 3, 4 ], error: Error: test error
       at Object.<anonymous> (C:\mypath\nodejs-module-labo\util\index.js:22:12)
       at Module._compile (internal/modules/cjs/loader.js:1063:30)
       at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
       at Module.load (internal/modules/cjs/loader.js:928:32)
       at Function.Module._load (internal/modules/cjs/loader.js:769:14)
       at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
       at internal/main/run_main_module.js:17:47, myself: [Circular *1] }

今回は、別のオブジェクトを間にはさんで間接的に自分自身を参照している、つまり循環参照しているオブジェクトがどのように表示されるのかを試しました。

文字列化したオブジェクトは以下です。

const obj = {};
const objProxy = {};
obj.objProxy = objProxy;
objProxy.obj = obj;

出力結果は以下のようになりました。

<ref *1> { objProxy: { obj: [Circular *1] } }

循環参照していても自分自身は[Circular *1]に変換して文字列に出力してくれるため、無限ループになっておかしくなることはないようです。