简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM