Dumping whole array: console.log and console.dir o

2019-01-25 04:22发布

问题:

I am trying to log a long array so I can copy it quickly in my terminal. However, if I try and log the array it looks like:

['item',
 'item',
  >>more items<<<
  ... 399 more items ]

How can I log the entire array so I can copy it really quickly?

回答1:

Setting maxArrayLength

There are a few methods all of which require setting maxArrayLength which otherwise defaults to 100.

  1. Provide the override as an option to console.log or console.dir

    console.log( myArry, {'maxArrayLength': null} );
    
  2. Set util.inspect.defaultOptions.maxArrayLength = null; which will impact all calls to console.log and util.format

  3. Call util.inspect yourself with options.

    const util = require('util')
    console.log(util.inspect(array, { maxArrayLength: null }))
    


回答2:

What's wrong with myArray.forEach(item => console.log(item))?



回答3:

Just found that option maxArrayLength works well with console.dir too:

console.dir(array, {depth: null, colors: true, maxArrayLength: null});



回答4:

Using console.table

Available in Node v10+, and all modern web-browsers, you can use console.table() instead, which will output a beautiful utf8 table where each row represents an element of the array.

> console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);

┌─────────┬─────┐
│ (index) │  a  │
├─────────┼─────┤
│    0    │  1  │
│    1    │ 'Z' │
└─────────┴─────┘


回答5:

Ugly but this will work:

function createFullArrayString(array){
  let string = '[';

  for(const item of array){
    string += `'${item}',\n`
  }

  string = string.substring(0, string.length - 2);

  string += ']';

  return string
}

console.log(createFullArrayString(array))

Wish there was a way to do this in native node.