How can I get the full object in Node.js's console.log(), rather than '[Object]'?

前端 未结 17 2925
一向
一向 2020-11-22 02:59

When debugging using console.log(), how can I get the full object?

const myObject = {
   \"a\":\"a\",
   \"b\":{
      \"c\":\"c\",
      \"d\":         


        
相关标签:
17条回答
  • 2020-11-22 03:24

    You can also do

    console.log(JSON.stringify(myObject, null, 3));
    
    0 讨论(0)
  • 2020-11-22 03:26

    JSON.stringify()

    let myVar = {a: {b: {c: 1}}};
    console.log(JSON.stringify( myVar, null, 4 ))
    

    Great for deep inspection of data objects. This approach works on nested arrays and nested objects with arrays.

    0 讨论(0)
  • 2020-11-22 03:28

    You can simply add an inspect() method to your object which will override the representation of object in console.log messages

    eg:

    var myObject = {
       "a":"a",
       "b":{
          "c":"c",
          "d":{
             "e":"e",
             "f":{
                "g":"g",
                "h":{
                   "i":"i"
                }
             }
          }
       }
    };
    myObject.inspect = function(){ return JSON.stringify( this, null, ' ' ); }
    

    then, your object will be represented as required in both console.log and node shell

    0 讨论(0)
  • 2020-11-22 03:28

    A simple trick would be use debug module to add DEBUG_DEPTH=null as environment variable when running the script

    Ex.

    DEBUG=* DEBUG_DEPTH=null node index.js

    In you code

    const debug = require('debug');
    debug("%O", myObject);
    
    0 讨论(0)
  • 2020-11-22 03:30

    Another simple method is to convert it to json

    console.log('connection : %j', myObject);
    
    0 讨论(0)
提交回复
热议问题