DauleDK
DauleDK

Reputation: 3443

Can I get the string value of console.table in nodejs?

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...

Upvotes: 6

Views: 5272

Answers (1)

Endless
Endless

Reputation: 37855

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')

Upvotes: 27

Related Questions