How to change string representation of objects in Nodejs debug console view

前端 未结 4 854
轮回少年
轮回少年 2020-12-15 06:24

How do I change the string representation of an object instance in nodejs debug console. Is there a method (like toString() in .NET) I can override?

4条回答
  •  既然无缘
    2020-12-15 06:40

    My two cents: How about overriding the console.log function to do what you want to. Here is the POC which needs a _toString function in any object to change the way it appears in the log.

    create a file logger.js with the following content:

    const getUpdatedLogObj = function(x){
    
    
        if(x && typeof x == 'object'){
                if(typeof x._toString === 'function'){
                    return x._toString()
                } else {
                    for(let i in x){
                        x[i] = getUpdatedLogObj(x[i])
                    }
                }
            }
            return x;
        }
    
    
    
        console._log = console.log
        console.log = function(x){console._log(getUpdatedLogObj({...x}))}
    

    import it in index.js

    require('./logger')
    
    console.log({a: 1, b: 2, c: {d: 5, e: 6, _toString: function(){return 'fromToString'}}})
    

    And you still get the navigaion:

提交回复
热议问题