node console.log() output array in one line

All we need is an easy explanation of the problem, so here it is.

I use node v10.6.0.

Here’s my codes:

console.log([{a:1, b:2}, {a:1, b:2}, {a:1, b:2}])
console.log([{a:1, b:2}, {a:1, b:2}, {a:1, b:2}, {a:1, b:2}, {a:1, b:2}, {a:1, b:2}, {a:1, b:2}, {a:1, b:2}, {a:1, b:2}])

the output is as following:

[ { a: 1, b: 2 }, { a: 1, b: 2 }, { a: 1, b: 2 } ]
[ { a: 1, b: 2 },
  { a: 1, b: 2 },
  { a: 1, b: 2 },
  { a: 1, b: 2 },
  { a: 1, b: 2 },
  { a: 1, b: 2 },
  { a: 1, b: 2 },
  { a: 1, b: 2 },
  { a: 1, b: 2 } ]

How can I make the second array output in one line, instead of spreading to multiple lines.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Although the output is not exactly the same as if console.log is used, it’s possible to use JSON.stringify to convert the array to a string, then print it:

console.log(JSON.stringify(array))

Try it online!

It cannot process circular structures, however.

Method 2

I suggest using the following:

console.log(util.inspect(array, {breakLength: Infinity}))

Plus, util.inspect has a bunch of extra options to format and limit the output:

https://nodejs.org/api/util.html#utilinspectobject-options

Method 3

Why not using console.table instead?

This give this nice table: https://tio.run/##y0osSyxOLsosKNHNy09J/Z9YVJRYaRtdnWhlqKOQZGVUq6NAW3bs/@T8vOL8nFS9ksSknFQNsAM0//8HAA

┌─────────┬───┬───┐
│ (index) │ a │ b │
├─────────┼───┼───┤
│    0    │ 1 │ 2 │
│    1    │ 1 │ 2 │
│    2    │ 1 │ 2 │
│    3    │ 1 │ 2 │
│    4    │ 1 │ 2 │
│    5    │ 1 │ 2 │
│    6    │ 1 │ 2 │
│    7    │ 1 │ 2 │
│    8    │ 1 │ 2 │
└─────────┴───┴───┘

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply