On this page

console 控制台

History
Source Code: lib/console.js

稳定性:2 - 稳定

node:console 模块提供了一个简单的调试控制台,类似于 Web 浏览器提供的 JavaScript 控制台机制。

该模块导出两个特定的组件:

  • 一个 Console 类,带有 console.log()、console.error() 和 console.warn() 等方法,可用于写入任意 Node.js 流。
  • 一个全局 console 实例,配置为写入 process.stdout 和 process.stderr。全局 console 无需调用 require('node:console') 即可使用。

警告:全局 console 对象的方法既不像与之相似的浏览器 API 那样始终同步,也不像其他所有 Node.js 流那样始终 异步。希望依赖 console 函数同步/异步行为的程序, 应先弄清 console 背后流的性质。这是因为 该流取决于底层平台以及当前进程的标准流 配置。有关更多信息, 请参阅 进程 I/O 说明 以了解更多信息。

使用全局 console 的示例:

console.log('hello world');
// 打印:hello world,输出到 stdout
console.log('hello %s', 'world');
// 打印:hello world,输出到 stdout
console.error(new Error('Whoops, something bad happened'));
// 将错误消息和堆栈跟踪打印到 stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// 打印:Danger Will Robinson! Danger!,输出到 stderr

使用 Console 类的示例:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// 打印:hello world,输出到 out
myConsole.log('hello %s', 'world');
// 打印:hello world,输出到 out
myConsole.error(new Error('Whoops, something bad happened'));
// 打印:[Error: Whoops, something bad happened],输出到 err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// 打印:Danger Will Robinson! Danger!,输出到 err

Console 类可用于创建具有可配置输出流的简单日志记录器, 可通过 require('node:console').Console 或 console.Console(或其解构形式)访问:

new Console(stdout, stderr?, ignoreErrors?): void
new Console(options): void
Attributes
options:<Object>
ignoreErrors:<boolean>
写入底层流时忽略错误。  默认值: true 。
colorMode:<boolean> | <string>
为此  Console 实例设置颜色支持。 设置为 true 时,在检查值时启用着色。设置为 false 时,在检查值时禁用着色。设置为 'auto' 时,颜色支持取决于相应流的 isTTY 属性值以及该流上 getColorDepth() 返回的值。如果同时设置了 inspectOptions.colors ,则不能使用此选项。 默认值: 'auto' 。
inspectOptions:<Object> | <Map>
指定传递给  util.inspect() 的选项。可以是选项对象,如果希望 stdout 和 stderr 使用不同选项,也可以是从流对象到选项的 Map 。
groupIndentation:<number>
设置分组缩进。  默认值: 2 。

创建一个带有一或两个可写流实例的 Console。stdout 是用于 打印日志或信息输出的可写流。stderr 用于警告或 错误输出。如果未提供 stderr,则 stdout 用作 stderr。

import { createWriteStream } from 'node:fs';
import { Console } from 'node:console';
// 或者
// const { Console } = console;

const output = createWriteStream('./stdout.log');
const errorOutput = createWriteStream('./stderr.log');
// 自定义简单日志记录器
const logger = new Console({ stdout: output, stderr: errorOutput });
// 像使用 console 一样使用它
const count = 5;
logger.log('count: %d', count);
// 在 stdout.log 中:count 5

全局 console 是一个特殊的 Console,其输出发送到 process.stdout 和 process.stderr。它等同于调用:

console.assert(value, ...message?): void
Attributes
value:<any>
用于测试是否为真值的值。
...message:<any>
除  value 之外的所有参数都用作错误消息。

如果 value 为假值或被省略,console.assert() 会写入 一条消息。它只写入消息,不会以其他方式影响执行。输出始终 以 "Assertion failed" 开头。如果提供了 message,则使用 util.format() 进行格式化。

如果 value 为真值,则不会发生任何事情。

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

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

console.assert();
// Assertion failed
M

console.clear

History
console.clear(): void

当 stdout 是 TTY 时,调用 console.clear() 将尝试清除 TTY。当 stdout 不是 TTY 时,此方法不执行任何操作。

console.clear() 的具体操作可能因操作系统 和终端类型而异。对于大多数 Linux 操作系统,console.clear() 的操作类似于 clear shell 命令。在 Windows 上,console.clear() 将只清除 Node.js 二进制文件当前终端视口中的 输出。

M

console.count

History
console.count(label?): void
Attributes
label:<string>
计数器的显示标签。 默认值: 'default' 。

维护一个特定于 label 的内部计数器,并向 stdout 输出 使用给定 label 调用 console.count() 的次数。

> console.count()
default: 1
undefined
> console.count('default')
default: 2
undefined
> console.count('abc')
abc: 1
undefined
> console.count('xyz')
xyz: 1
undefined
> console.count('abc')
abc: 2
undefined
> console.count()
default: 3
undefined
>
M

console.countReset

History
console.countReset(label?): void
Attributes
label:<string>
计数器的显示标签。 默认值: 'default' 。

重置特定于 label 的内部计数器。

> console.count('abc');
abc: 1
undefined
> console.countReset('abc');
undefined
> console.count('abc');
abc: 1
undefined
>
console.debug(data, ...args?): void
Attributes
data:<any>
...args:<any>

console.debug() 函数是 console.log() 的别名。

M

console.dir

History
console.dir(obj, options?): void
Attributes
obj:<any>
options:<Object>
showHidden:<boolean>
若为  true ,还会显示对象的不可枚举属性和 symbol 属性。 默认值: false 。
depth:<number>
告诉  util.inspect() 在格式化对象时递归 多少层。这对于检查大型复杂对象很有用。 若要无限递归,请传入 null 。 默认值: 2 。
colors:<boolean>
若为  true ,输出将使用 ANSI 颜色 代码设置样式。颜色可自定义; 请参阅 自定义 util.inspect() 颜色 。 默认值: false 。

对 obj 使用 util.inspect() 并将结果字符串打印到 stdout。 此函数会绕过 obj 上定义的任何自定义 inspect() 函数。

console.dirxml(...data): void
Attributes
...data:<any>

此方法调用 console.log() 并将收到的参数传给该调用。 此方法不产生任何 XML 格式。

M

console.error

History
console.error(data?, ...args?): void
Attributes
data:<any>
...args:<any>

带换行打印到 stderr。可以传入多个参数, 第一个用作主要消息,其余参数用作类似 printf(3) 的 替换值(所有参数都会传给 util.format())。

const code = 5;
console.error('error #%d', code);
// 打印:error #5,输出到 stderr
console.error('error', code);
// 打印:error 5,输出到 stderr

如果第一个字符串中未找到格式元素(例如 %d),则会对每个参数调用 util.inspect() 并拼接得到的字符串 值。有关更多信息,请参阅 util.format()。

M

console.group

History
console.group(...label?): void
Attributes
...label:<any>

按 groupIndentation 指定的 空格数增加后续行的缩进。

如果提供了一个或多个 label,会先打印它们且不 附加额外缩进。

M

console.groupCollapsed

History
console.groupCollapsed(): void

console.group() 的别名。

M

console.groupEnd

History
console.groupEnd(): void

按 groupIndentation 指定的 空格数减少后续行的缩进。

M

console.info

History
console.info(data?, ...args?): void
Attributes
data:<any>
...args:<any>

console.info() 函数是 console.log() 的别名。

M

console.log

History
console.log(data?, ...args?): void
Attributes
data:<any>
...args:<any>

带换行打印到 stdout。可以传入多个参数, 第一个用作主要消息,其余参数用作类似 printf(3) 的 替换值(所有参数都会传给 util.format())。

const count = 5;
console.log('count: %d', count);
// 打印:count: 5,输出到 stdout
console.log('count:', count);
// 打印:count: 5,输出到 stdout

有关更多信息,请参阅 util.format()。

M

console.table

History
console.table(tabularData, properties?): void
Attributes
tabularData:<any>
properties:<string>
[] 用于构造表格的备用属性。

尝试用 tabularData 的属性作为列(或使用 properties) 并以 tabularData 作为行来构造表格并记录。如果无法解析为表格数据, 则退化为只记录该参数。

// 这些无法解析为表格数据
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' │
// └─────────┴─────┘
M

console.time

History
console.time(label?): void
Attributes
label:<string>
默认值: 'default'

启动一个可用于计算操作持续时间的计时器。计时器 由唯一的 label 标识。调用 console.timeEnd() 时使用相同的 label 停止计时器,并以 合适的时间单位将经过的时间输出到 stdout。例如,如果经过 时间为 3869ms,console.timeEnd() 会显示 "3.869s"。

console.timeEnd(label?): void
Attributes
label:<string>
默认值: 'default'

停止之前通过调用 console.time() 启动的计时器,并 将结果打印到 stdout:

console.time('bunch-of-stuff');
// 执行一堆操作。
console.timeEnd('bunch-of-stuff');
// 打印:bunch-of-stuff: 225.438ms
M

console.timeLog

History
console.timeLog(label?, ...data?): void
Attributes
label:<string>
默认值: 'default'
...data:<any>

对于之前通过调用 console.time() 启动的计时器,将 经过的时间和其他 data 参数打印到 stdout:

console.time('process');
const value = expensiveProcess1(); // Returns 42
console.timeLog('process', value);
// 打印 "process: 365.227ms 42"。
doExpensiveProcess2(value);
console.timeEnd('process');
M

console.trace

History
console.trace(message?, ...args?): void
Attributes
message:<any>
...args:<any>

向 stderr 打印字符串 'Trace: ',后跟由 util.format() 格式化的消息以及代码中当前位置的堆栈跟踪。

console.trace('Show me');
// 打印:(堆栈跟踪会因调用 trace 的位置而异)
//  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)
M

console.warn

History
console.warn(data?, ...args?): void
Attributes
data:<any>
...args:<any>

console.warn() 函数是 console.error() 的别名。

以下方法由 V8 引擎在通用 API 中暴露,但与 检查器(--inspect 标志)配合使用时 才会显示内容。

M

console.profile

History
console.profile(label?): void
Attributes
label:<string>

除非在检查器中使用,否则此方法不显示任何内容。 console.profile() 方法会启动一次 JavaScript CPU 性能分析,可选地使用 一个标签,直到调用 console.profileEnd() 为止。随后该性能分析会添加到 检查器的 Profile 面板。

console.profile('MyLabel');
// 一些代码
console.profileEnd('MyLabel');
// 将性能分析 'MyLabel' 添加到检查器的 Profiles 面板。
M

console.profileEnd

History
console.profileEnd(label?): void
Attributes
label:<string>

除非在检查器中使用,否则此方法不显示任何内容。如果已经启动, 则停止当前的 JavaScript CPU 性能分析会话,并将 报告打印到检查器的 Profiles 面板。请参阅 console.profile() 获取示例。

如果调用此方法时未提供标签,则最近启动的性能分析 会被停止。

M

console.timeStamp

History
console.timeStamp(label?): void
Attributes
label:<string>

除非在检查器中使用,否则此方法不显示任何内容。 console.timeStamp() 方法会向检查器的 Timeline 面板 添加一个标签为 'label' 的事件。