使用 Node.js 输出到命令行

使用 console 模块的基本输出

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

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

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

如果你传递一个对象,它会将其呈现为字符串。

你可以将多个变量传递给 console.log,例如

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

console.log(x, y);

Node.js 将打印两者。

我们还可以通过传递变量和格式说明符来格式化漂亮的短语。

例如

console.log('My %s has %d ears', 'cat', 2);
  • %s 将变量格式化为字符串
  • %d 将变量格式化为数字
  • %i 仅将变量格式化为整数部分
  • %o 将变量格式化为对象

示例

console.log('%o', Number);

清除控制台

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') 的调用如何将值计数器重置为零。

在某些情况下,打印函数的调用堆栈跟踪可能很有用,也许是为了回答问题你是如何到达代码的那部分的?

你可以使用 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()');
  // do something, and measure the time it takes
  doSomething();
  console.timeEnd('doSomething()');
};
measureDoingSomething();

stdout 和 stderr

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

console.error 打印到 stderr 流。

它不会出现在控制台中,但它会出现在错误日志中。

为输出着色

注意 此资源的这一部分是使用版本 22.11 设计的,该版本将 styleText 标记为“主动开发”。

在许多情况下,你会被诱惑粘贴某些文本以在终端获得漂亮的输出。

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

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

import { styleText } from 'node:util';

然后,你可以使用它来设置你的文本样式

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

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