Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

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...
like image 874
DauleDK Avatar asked Dec 22 '22 16:12

DauleDK


1 Answers

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 dose 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')
like image 95
Endless Avatar answered Jan 30 '23 07:01

Endless