node:console 模块提供了一个简单的调试控制台,类似于网络浏览器提供的 JavaScript 控制台机制。
node:console 模块提供了一个简单的调试控制台,类似于网络浏览器提供的 JavaScript 控制台机制。
该模块输出两个特定组件:
全局控制台对象的方法既不像其类似的浏览器 API 那样始终是同步的,也不像所有其他 Node.js 流那样始终是异步的。更多信息,请参阅有关进程 I/O 的说明。
使用全局控制台(console)的示例:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to 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!`);
// Prints: Danger Will Robinson! Danger!, to stderr
使用控制台类的示例:
import { Console } from "node:console";
import { createWriteStream } from "node:fs";
import { join } from "node:path";
import { URL, fileURLToPath } from "node:url";
const __dirname = fileURLToPath(new URL("../../", import.meta.url));
const ouput = createWriteStream(join(__dirname, "src/console/stdout.log"));
const errOutput = createWriteStream(join(__dirname, "src/console/stderr.log"));
const logger = new Console({ stdout: ouput, stderr: errOutput });
const count = 5;
logger.log("count : %d", count);
logger.log("hello world");
// Prints: hello world, to out
logger.log("hello %s", "world");
// Prints: hello world, to out
logger.error(new Error("Whoops, something bad happened"));
// Prints: [Error: Whoops, something bad happened], to err
const name = "Will Robinson";
logger.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
Console 类可用于创建具有可配置输出流的简单日志记录器,并可使用 require(‘node:console’).Console 或 console.Console(或它们的重组对应类)访问:
const { Console } = require('node:console');
// or
const { Console } = console;
参数:
创建一个新的 Console,其中包含一个或两个可写流实例。stdout 是一个可写流,用于打印日志或信息输出。stderr 用于警告或错误输出。如果没有提供 stderr,则使用 stdout 代替 stderr。
import { Console } from "node:console";
import { createWriteStream } from "node:fs";
import { join } from "node:path";
import { URL, fileURLToPath } from "node:url";
const __dirname = fileURLToPath(new URL("../../", import.meta.url));
const ouput = createWriteStream(join(__dirname, "src/console/stdout.log"));
const errOutput = createWriteStream(join(__dirname, "src/console/stderr.log"));
const logger = new Console({ stdout: ouput, stderr: errOutput });
const count = 5;
logger.log("count : %d", count);
logger.log("hello world");
// Prints: hello world, to out
logger.log("hello %s", "world");
// Prints: hello world, to out
logger.error(new Error("Whoops, something bad happened"));
// Prints: [Error: Whoops, something bad happened], to err
const name = "Will Robinson";
logger.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
全局控制台是一个特殊的控制台,其输出会发送到 process.stdout 和 process.stderr。它相当于调用:
const global = new Console({ stdout: process.stdout, stderr: process.stderr });
global.log("12323");
console.assert() 会在值有误或省略时写入一条信息。它只会写入一条信息,不会影响执行。输出总是以 "断言失败 "开头。如果提供了信息,则使用 util.format() 格式化信息。
如果值是真实的,则什么也不会发生。
console.assert(true, 'does nothing');
console.assert(false, 'Whoops %s work', 'didn\'t');
// Assertion failed: Whoops didn't work
console.assert();
// Assertion failed
当 stdout 是 TTY 时,调用 console.clear() 将尝试清除 TTY。当 stdout 不是 TTY 时,该方法不起任何作用。
TTY —— TTY是由虚拟控制台,串口以及伪终端设备组成的终端设备。
console.clear() 的具体操作可能因操作系统和终端类型而异。对于大多数 Linux 操作系统,console.clear() 的操作类似于 clear shell 命令。在 Windows 操作系统中,console.clear() 只清除 Node.js 二进制当前终端视口中的输出。
参数:
维护一个特定于标签的内部计数器,并将调用给定标签的 console.count() 次数输出到 stdout。
> 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
>
重置标签专用的内部计数器。
console.count("abc");
console.countReset("abc");
console.count("abc");
console.debug() 函数是 console.log() 的别名。
在调试模式下这个语句相当于在此处打了一下断点。
参数:
在 obj 上使用 util.inspect(),并将结果字符串打印到 stdout。此函数会绕过在 obj 上定义的任何自定义 inspect() 函数。
该方法调用 console.log(),并将收到的参数传递给它。该方法不会生成任何 XML 格式。
console.dir(`[1,
2,
3]`);
console.log(`[1,
2,
3]`);
console.dirxml(`[1,
2,
3]`);
以换行方式打印到 stderr。可以传递多个参数,第一个参数作为主要信息,所有其他参数作为替代值,类似于 printf(3)(参数全部传递给 util.format())。
const code = 5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr
根据 groupIndentation 长度,增加后续行的缩进空格。
如果提供了一个或多个标签,则先打印这些标签,而不增加缩进。
console.group() 的别名。
根据 groupIndentation 长度,以空格减少后续行的缩进。
console.log(1);
console.group();
console.log(2);
console.groupEnd();
console.log(3);
console.info() 函数是 console.log() 的别名。
以换行方式打印到 stdout。可以传递多个参数,第一个参数作为主要信息,所有其他参数作为替代值,类似于 printf(3)(参数全部传递给 util.format())。
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
更多信息请参见 util.format()。
参数:
// 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' │
// └─────────┴─────┘
console.table(
[
{ a: 1, b: "Y" },
{ a: "Z", b: 2 },
],
["a", "b", "c"]
);
启动计时器,用于计算操作的持续时间。定时器由一个唯一的标签标识(label)。调用 console.timeEnd() 停止计时器并以合适的时间单位向 stdout 输出经过的时间时,请使用相同的标签。例如,如果经过时间为 3869ms,则 console.timeEnd() 会显示 “3.869s”。
停止之前通过调用 console.time() 启动的计时器,并将结果打印到 stdout:
console.time('bunch-of-stuff');
// Do a bunch of stuff.
console.timeEnd('bunch-of-stuff');
// Prints: bunch-of-stuff: 225.438ms
对于之前通过调用 console.time() 启动的计时器,会将经过的时间和其他数据参数打印到 stdout:
console.time('process');
const value = expensiveProcess1(); // Returns 42
console.timeLog('process', value);
// Prints "process: 365.227ms 42".
doExpensiveProcess2(value);
console.timeEnd('process');
向 stderr 打印字符串 “Trace:”,然后是 util.format() 格式化的信息和代码中当前位置的堆栈跟踪。
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. (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)
console.warn() 函数是 console.error() 的别名。
V8 引擎在通用 API 中公开了以下方法,但除非与检查器(–inspect 标志)一起使用,否则不会显示任何内容。
除非在检查器中使用,否则该方法不会显示任何内容。console.profile() 方法会启动一个带有可选标签的 JavaScript CPU 配置文件,直到调用 console.profileEnd()。然后,该配置文件将添加到检查器的配置文件面板中。
console.profile('MyLabel');
// Some code
console.profileEnd('MyLabel');
// Adds the profile 'MyLabel' to the Profiles panel of the inspector.
除非在检查器中使用,否则该方法不会显示任何内容。如果当前 JavaScript CPU 剖析会话已启动,则停止该会话,并将报告打印到检查器的 Profiles 面板。有关示例,请参阅 console.profile()。
如果调用此方法时没有标签,则会停止最近启动的配置文件。
除非在检查器中使用,否则该方法不会显示任何内容。console.timeStamp() 方法会在检查器的时间线面板中添加一个标有 "label "的事件。
结束了。