Nodejs 运行pm2 start app.js -i max报错Converting circular structure to JSON
Nodejs 运行pm2 start app.js -i max报错Converting circular structure to JSON
{ online: true, success: true, pid: 14744 }
/usr/local/lib/node_modules/pm2/node_modules/axon/lib/sockets/sock.js:122
msg.write(codec.encode(data[i]), codec.id);
^
TypeError: Converting circular structure to JSON
at Object.stringify [as encode] (native)
at RepSocket.Socket.pack (/usr/local/lib/node_modules/pm2/node_modules/axon/lib/sockets/sock.js:122:23)
at reply (/usr/local/lib/node_modules/pm2/node_modules/axon/lib/sockets/rep.js:60:25)
at Server.onmessage (/usr/local/lib/node_modules/pm2/node_modules/axon-rpc/lib/server.js:91:5)
at ex (/usr/local/lib/node_modules/pm2/lib/God.js:208:32)
at God.prepare (/usr/local/lib/node_modules/pm2/lib/God.js:214:16)
at God.executeApp (/usr/local/lib/node_modules/pm2/lib/God.js:183:15)
at Worker.module.exports.God.nodeApp (/usr/local/lib/node_modules/pm2/lib/God/ClusterMode.js:68:22)
at Worker.g (events.js:185:14)
at Worker.EventEmitter.emit (events.js:85:17)
2 回复
当你使用 pm2 start app.js -i max
启动应用时,如果遇到 Converting circular structure to JSON
错误,通常是因为你的应用中存在循环引用的对象。这种错误发生在尝试将对象转换为 JSON 字符串时,JavaScript 的内置 JSON.stringify()
函数无法处理循环引用的情况。
例如,假设你有一个对象结构如下:
const obj = {};
obj.self = obj;
当你尝试将这样的对象转换为 JSON 字符串时,会触发该错误。
解决方案
-
检查并修正循环引用: 找到并修正代码中的循环引用问题。你可以使用第三方库如
circular-json
来处理这种情况。const CircularJSON = require('circular-json'); console.log(CircularJSON.stringify(obj));
-
使用递归函数手动处理对象: 如果你需要自定义处理逻辑,可以编写一个递归函数来遍历对象并处理循环引用。
function safeStringify(obj, indentation = 2) { const seen = new WeakSet(); return JSON.stringify(obj, (key, value) => { if (typeof value === 'object' && value !== null) { if (seen.has(value)) { return; // 忽略循环引用 } seen.add(value); } return value; }, indentation); } console.log(safeStringify(obj));
通过上述方法,你可以解决 Converting circular structure to JSON
错误,并正常启动应用。