本页内容

Node.js 提供 console 模块,它提供了大量与命令行交互的实用方法。

它基本上与你在浏览器中看到的 console 对象相同。

最基本且最常用的方法是 console.log(),它将你传入的字符串打印到控制台。

如果传入一个对象,它会将其渲染为字符串。

你可以向 console.log 传入多个变量,例如:

const x = 'x';
const y = 'y';

console.log(x, y);

Node.js 会同时打印两者。

我们还可以通过传入变量和格式说明符来格式化内容:

例如:

  • %s 将变量格式化为字符串
  • %d 将变量格式化为数字
  • %i 只将变量的整数部分格式化
  • %o 将变量格式化为对象

示例:

console.clear() 会清空控制台(具体行为可能取决于所使用的控制台)

console.count() 是一个方便的方法。

看这段代码:

const x = 1;
const y = 2;
const z = 3;

console.count(
  'The value of x is ' + x + ' and has been checked .. how many times?'
);

console.count(
  'The value of x is ' + x + ' and has been checked .. how many times?'
);

console.count(
  'The value of y is ' + y + ' and has been checked .. how many times?'
);

发生的情况是,console.count() 会统计某个字符串被打印的次数,并在旁边打印计数:

你也可以只统计苹果和橙子:

const oranges = ['orange', 'orange'];
const apples = ['just one apple'];

oranges.forEach(fruit => {
  console.count(fruit);
});
apples.forEach(fruit => {
  console.count(fruit);
});

console.countReset() 方法会重置 console.count() 使用的计数器。

我们将用苹果和橙子的例子来演示这一点。

const oranges = ['orange', 'orange'];
const apples = ['just one apple'];

oranges.forEach(fruit => {
  console.count(fruit);
});
apples.forEach(fruit => {
  console.count(fruit);
});

console.countReset('orange');

oranges.forEach(fruit => {
  console.count(fruit);
});

注意 console.countReset('orange') 调用如何将 'orange' 的计数重置为零。

有些情况下,打印函数的调用堆栈跟踪很有用,或许是为了回答_你是如何到达代码这一部分的?_

你可以使用 console.trace():

const function2 = () => console.trace();
const function1 = () => function2();
function1();

这将打印堆栈跟踪。如果在 Node.js REPL 中尝试,会打印如下内容:

Trace
    at function2 (repl:1:33)
    at function1 (repl:1:25)
    at repl:1:1
    at ContextifyScript.Script.runInThisContext (vm.js:44:33)
    at REPLServer.defaultEval (repl.js:239:29)
    at bound (domain.js:301:14)
    at REPLServer.runBound [as eval] (domain.js:314:12)
    at REPLServer.onLine (repl.js:440:10)
    at emitOne (events.js:120:20)
    at REPLServer.emit (events.js:210:7)

使用 time() 和 timeEnd() 可以轻松计算函数运行所需的时间:

const doSomething = () => console.log('test');
const measureDoingSomething = () => {
  console.time('doSomething()');
  // 执行某些操作,并测量所需时间
  doSomething();
  console.timeEnd('doSomething()');
};
measureDoingSomething();

正如我们所见,console.log 非常适合在控制台中打印消息。这就是所谓的标准输出,即 stdout。

console.error 打印到 stderr 流。

它会出现在控制台中,但可以与常规输出分开处理。

注意 本部分内容基于 22.11 版本编写,该版本将 styleText 标记为“活跃开发中”。

很多时候,你会想粘贴某些文本,以便在终端中获得漂亮的输出。

node:util 模块提供了一个 styleText 函数。让我们看看如何使用它。

首先,你需要从 node:util 模块导入 styleText 函数:

然后,你可以用它为文本设置样式:

console.log(
  styleText(['red'], 'This is red text ') +
    styleText(['green', 'bold'], 'and this is green bold text ') +
    'this is normal text'
);

第一个参数是样式数组,第二个参数是要设置样式的文本。我们邀请你阅读文档。