Skip to content

1.Class Console

基础用法:new Console(options)

options 基本用法如下:

  • stdout
  • stderr
  • ignoreErrors
  • colorMode
  • inspectOptions
  • groupIndentation

The global console is a special Console whose output is sent to process.stdout and process.stderr

js
// console
console.log()
console.error()

// new Console
new Console({
  stdout: process.stdout,
  stderr: process.stderr
})
js
const fs = require('node:fs')
const path = require('node:path')
const console = require('node:console')
const { Console } = console

const output = fs.createWriteStream(path.resolve(__dirname, './logs/stdout.log'))
const errorOutput = fs.createWriteStream(path.resolve(__dirname, './logs/stderr.log'))

// Custom simple logger
const logger = new Console({ stdout: output, stderr: errorOutput })

// use it like console
const count = 5
logger.log('count: %d', count)
// In stdout.log: count 5

2.console.assert

基础用法:console.assert(value[,...message])

js
console.assert(true, 'does nothing')

console.assert(false, 'Whoops %s work', 'didn\'t')
// Assertion failed: Whoops didn't work

console.assert(false)

console.assert()
// Assertion failed

3.console.clear

js
// 效果等同于 `shell` 的 `clear` 命令
console.clear()

4.console.count

js
console.count()
// default: 1

console.count('default')
// default: 2

console.count('abc')
// abc: 1

console.count('xyz')
// xyz: 1

console.count('abc')
// abc: 2

console.count()
// default: 3

console.countReset() // 重置计数器

console.count()
// default: 1

5.console.dir

console.dir(obj[,options])

  • showHidden 展示不可枚举属性或者 symbol 属性 默认为 false
  • depth 遍历深度 默认为 2 如果想要展示所有属性 可设置改属性为 null
  • colors

实际测试了下,下例中的 console.dirconsole.log 表现基本一致:

js
const obj = {
  name: 'Alice',
  age: 30,
  details: {
    hobbies: ['reading', 'biking'],
    education: {
      degree: 'Bachelor',
      year: 2015
    }
  }
}

console.log('Using console.log:')
console.log(obj)

console.log('Using console.dir:')
console.dir(obj, { depth: 2, colors: true })

6.console.error

console.error([data][,...args])

该方法可用于打印 stderr 至控制台

其他形式:console.warn()

js
const code = 5
console.error('error #%d', code)
// Prints: error #5, to stderr

console.error('error', code)
// Prints: error 5, to stderr

// console.log(process.stderr.toString())

7.console.log

console.log([data][,...args])

其中 data 参数可使用形式符

  • %s:字符串将用于转换除 BigIntObject-0 之外的所有值。BigInt 值将用一个 n 表示,没有用户定义 toString 函数的对象将使用 util.inspect() 进行检查,选项为 { depth: 0, colors: false, compact: 3 }
  • %d:数字将用于转换除 BigIntSymbol 之外的所有值。
  • %iparseInt(value, 10) 用于转换除 BigIntSymbol 之外的所有值。
  • %fparseFloat(value) 用于转换除 Symbol 之外的所有值。
  • %jJSON。如果参数包含循环引用,则替换为字符串 [Circular]
  • %o:对象。对象的字符串表示,使用通用 JavaScript 对象格式。类似于 util.inspect(),选项为 { showHidden: true, showProxy: true }。这将显示完整对象,包括不可枚举的属性和代理。
  • %O:对象。对象的字符串表示,使用通用 JavaScript 对象格式。类似于没有选项的 util.inspect()。这将显示完整对象,但不包括不可枚举的属性和代理。
  • %cCSS。此说明符被忽略,将跳过任何传入的 CSS
  • %%:单个百分号 (%)。这不会消耗任何参数。

其他形式:

  • console.debug()
  • console.info()
js
const count = 5
console.log('count: %d', count)
// Prints: count: 5, to stdout

console.log('count:', count)
// Prints: count: 5, to stdout

8.console.table

console.table(tabularData[,properties])

console.table 方法用于在控制台输出一个表格,该表格包含一个数组或对象数组,该数组或对象数组的元素可以是任何类型。

js
// These can't be parsed as tabular data
console.table(Symbol())
// Symbol()

console.table(undefined)
// undefined

console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }])
// ┌─────────┬─────┬─────┐
// │ (index) │ a   │ b   │
// ├─────────┼─────┼─────┤
// │ 0       │ 1   │ 'Y' │
// │ 1       │ 'Z' │ 2   │
// └─────────┴─────┴─────┘

console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a'])
// ┌─────────┬─────┐
// │ (index) │ a   │
// ├─────────┼─────┤
// │ 0       │ 1   │
// │ 1       │ 'Z' │
// └─────────┴─────┘

9.console.time

js
console.time([label])

console.timeLog([label][,...data])

console.timeEnd([label])
js
console.time('process')

const value = 42
console.timeLog('process', value)
// Prints "process: 365.227ms 42".

console.timeEnd('process')

10.console.trace

js
console.trace('Show me')
// Prints: (stack trace will vary based on where trace is called)
//  Trace: Show me
//    at repl:2:9
//    at REPLServer.defaultEval (repl.js:248:27)
//    at bound (domain.js:287:14)
//    at REPLServer.runBound [as eval] (domain.js:300:12)
//    at REPLServer.<anonymous> (repl.js:412:12)
//    at emitOne (events.js:82:20)
//    at REPLServer.emit (events.js:169:7)
//    at REPLServer.Interface._onLine (readline.js:210:10)
//    at REPLServer.Interface._line (readline.js:549:8)
//    at REPLServer.Interface._ttyWrite (readline.js:826:14)