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...
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With