node:console
和 process 一样,console 模块也被暴露在了全局作用域当中
断言
在平时的调试当中,我们会尝试打印一些值,确认是否符合预期,等正式发布后删除掉。实际上,我们可以使用 console 的断言功能
console.assert(true, 'does nothing')
console.assert(false, 'Whoops %s work', 'didn\'t')
// Assertion failed: Whoops didn't work
console.assert()
// Assertion failed
console.assert(1 + 2 == 4, 'Calculation error')
// Assertion failed: Calculation error如果 console.assert 方法的第一个参数值为 true ,不会有任何输出 如果 console.assert 方法的第一个参数值为 false ,则会输出后面的内容
创建一个实例
通过 new Console() 的方式可以自定义一个实例,平时我们使用的 console,实际等价于指定参数为 process.stdout 和 process.stderr
import { Console } from 'node:console'
const logger = new Console(process.stdout, process.stderr)
// 调用下面二者效果是一样的
logger.log('hello')
console.log('hello')可以看到,Console 构造函数支持两个参数,分别是输出流和错误流。所以我们可以传入文件流,来达到直接写文件的目的
import fs from 'node:fs'
import { Console } from 'node:console'
const output = fs.createWriteStream('stout.log')
const errOutput = fs.createWriteStream('stderr.log')
const logger = new Console(output, errOutput)
logger.log('succeed')
logger.error('fail')深度输出
默认的 console.log 只会输出三层的数据,如果想要显示全部的数据,可以通过如下方式
import { inspect } from 'node:util'
const myObject = {
key1: 'value1',
key2: 'value2',
key3: {
nestedKey: 'nestedValue'
}
}
console.log(inspect(myObject, { depth: null }))