Vencovsky
Vencovsky

Reputation: 31683

How to solve Converting circular structure to JSON in node?

I was watching a course that showed how to make an console.log with custom configs, like the color or depending on your env mode, you show the log or not.

But i keep getting the error TypeError: Converting circular structure to JSON and I don't know why this is happening and how to solve it.

In the course, that works fine, but it doesn't to me.

node version => v8.11.2

require('colors')
const _ = require('lodash')

const config = require('../config/config')

const noop = () => { }

const consoleLog = config.logging ? console.log.bind(console) : noop

const logger = {
    log: () => {
        const args = _.toArray(arguments)
            .map(arg => {
                if (typeof arg === 'object') {
                    let str = JSON.stringify(arg, 2)
                    return str.magenta
                } else {
                    arg += ''
                    return arg.magenta
                }
            })
        consoleLog.apply(console, args)
    }
}

module.exports = logger

Edit1: arguments can be anything, since logger will be used to log things with different colors in the console.

logger.log('some thing you want to log')

Upvotes: 0

Views: 83

Answers (1)

vsemozhebuty
vsemozhebuty

Reputation: 13812

logger.log() is an arrow function, so arguments are not arguments of this function (see Arrow functions: No binding of arguments), but arguments of a parent function, in this case — Node.js wrapper function that compiles modules and has arguments with circular dependencies.

Try to use common function here:

const logger = {
  log() {
    // ...
  }
};

Upvotes: 2

Related Questions