5

I'm implementing a pretty format for my Winston logger, and was wondering If could use the Node.js method console.table to get the "string"?

The method is void, but is there somehow I could the string representation?

const tableAsString = console.table([{foo: 'bar'}, {foo: 'bar2'}])
// This does not work, table as string is undefined...
InSync
  • 4,851
  • 4
  • 8
  • 30
DauleDK
  • 3,313
  • 11
  • 55
  • 98
  • `console.table` does not return anything. You can see the source code here https://github.com/nodejs/node/blob/v14.9.0/lib/internal/console/constructor.js#L457 – Molda Sep 04 '20 at 09:04
  • Thanks for providing the link to the source code. The code is difficult for me to understand - does it even build a string internally? – DauleDK Sep 04 '20 at 09:07
  • Yes, this is where it renders(builds the string) the actual table https://github.com/nodejs/node/blob/v14.9.0/lib/internal/cli_table.js – Molda Sep 04 '20 at 09:21
  • 1
    Note however that the `cli_table` function is never exported so you don't have access to it. I strongly suggest you give up this path and instead look at npm for solutions. I've personally had good results using `columnify`: https://www.npmjs.com/package/columnify – slebetman Sep 04 '20 at 09:25
  • 1
    console.table should come with an option to return as string. – WEBjuju May 26 '23 at 14:59

1 Answers1

20

There is actually one easy way to do this in NodeJS

You can construct a own Console instances and use a custom output stream.

import { Console } from 'node:console'
import { Transform } from 'node:stream'

const ts = new Transform({ transform(chunk, enc, cb) { cb(null, chunk) } })
const logger = new Console({ stdout: ts })

function getTable (data) {
  logger.table(data)
  return (ts.read() || '').toString()
}

const str = getTable({foo: 'bar'})
console.log(str.length) // 105
console.log(str)
// ┌─────────┬────────┐
// │ (index) │ Values │
// ├─────────┼────────┤
// │   foo   │ 'bar'  │
// └─────────┴────────┘

I created a package called: Not a log that does exactly this with the help of Proxy to make all methods on the Console instances return a string in just 20 lines of code! Usage:

import logger from 'not-a-log'

const string = logger.table([{foo: 'bar'}, {foo: 'bar2'}])
const count = logger.count('made a request')
const foo = logger.log('identity foo')
WEBjuju
  • 5,797
  • 4
  • 27
  • 36
Endless
  • 34,080
  • 13
  • 108
  • 131