我可以在nodejs中获取console.table的字符串值吗?

Dau*_*eDK 3 node.js

我正在为我的 Winston 记录器实现一种漂亮的格式,并且想知道是否可以使用 Node.js 方法console.table来获取“字符串”?

该方法是无效的,但是我可以以某种方式表示字符串吗?

const tableAsString = console.table([{foo: 'bar'}, {foo: 'bar2'}])
// This does not work, table as string is undefined...
Run Code Online (Sandbox Code Playgroud)

End*_*ess 5

在 NodeJS 中实际上有一种简单的方法可以做到这一点

您可以构建自己的控制台实例并使用自定义输出流。

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'  ?
// ????????????????????
Run Code Online (Sandbox Code Playgroud)

我创建了一个名为:Not a log在 Proxy 的帮助下完全满足此要求,使Console 实例上的所有方法仅用 20 行代码就返回一个字符串!用法:

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')
Run Code Online (Sandbox Code Playgroud)