On this page

🌐 Output to the command line using Node.js

🌐 Basic output using the console module

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

🌐 Node.js provides a console module which provides tons of very useful ways to interact with the command line.

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

🌐 It is basically the same as the console object you find in the browser.

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

🌐 The most basic and most used method is console.log(), which prints the string you pass to it to the console.

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

🌐 If you pass an object, it will render it as a string.

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

🌐 You can pass multiple variables to console.log, for example:

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

console.log(x, y);

Node.js 将打印两者。

🌐 and Node.js will print both.

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

🌐 We can also format pretty phrases by passing variables and a format specifier.

例如:

🌐 For example:

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

示例:

🌐 Example:

🌐 Clear the console

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

🌐 Counting elements

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

拿这个代码:

🌐 Take this code:

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() 会计算某个字符串被打印的次数,并在旁边显示计数:

🌐 What happens is that console.count() will count the number of times a string is printed, and print the count next to it:

你可以只计算苹果和橘子:

🌐 You can just count apples and oranges:

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

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

🌐 Reset counting

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

🌐 The console.countReset() method resets counter used with console.count().

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

🌐 We will use the apples and orange example to demonstrate this.

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

🌐 Notice how the call to console.countReset('orange') resets the value counter to zero.

🌐 Print the stack trace

在某些情况下,打印函数的调用栈跟踪可能会很有用,也许是为了回答“你是怎么到达代码的这一部分的?”这个问题。

🌐 There might be cases where it's useful to print the call stack trace of a function, maybe to answer the question how did you reach that part of the code?

你可以使用 console.trace() 来实现这一点:

🌐 You can do so using console.trace():

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

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

🌐 This will print the stack trace. This is what's printed if we try this in the 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)

🌐 Calculate the time spent

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

🌐 You can easily calculate how much time a function takes to run, using time() and 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 and stderr

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

🌐 As we saw console.log is great for printing messages in the Console. This is what's called the standard output, or stdout.

console.error 会输出到 stderr 流。

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

🌐 It will appear in the console, but can be handled separately from regular output.

🌐 Color the output

注意 该资源部分是基于版本 22.11 设计的,该版本将 styleText 标记为“活跃开发中”。

在许多情况下,你会倾向于粘贴某些文本以在终端上获得不错的输出。

🌐 In many cases, you will be tempted to paste certain text to get a nice output at the terminal.

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

🌐 There is a styleText function provided by the node:util module. Let's discover how to use it.

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

🌐 First of all, you need to import the styleText function from the node:util module:

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

🌐 Then, you can use it to style your text:

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

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

🌐 The first argument is an array of styles, and the second argument is the text you want to style. We invite you to read the docs