使用 Node.js 输出到命令行
¥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:
console.log('My %s has %d ears', 'cat', 2);
-
%s
将变量格式化为字符串¥
%s
format a variable as a string -
%d
将变量格式化为数字¥
%d
format a variable as a number -
%i
仅将变量格式化为其整数部分¥
%i
format a variable as its integer part only -
%o
将变量格式化为对象¥
%o
format a variable as an object
示例:
¥Example:
console.log('%o', Number);
清除控制台
¥Clear the console
console.clear()
清除控制台(行为可能取决于所使用的控制台)
¥console.clear()
clears the console (the behavior might depend on the console used)
计数元素
¥Counting elements
console.count()
是一种方便的方法。
¥console.count()
is a handy method.
获取此代码:
¥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 和 stderr
¥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
流。
¥console.error
prints to the stderr
stream.
它不会出现在控制台中,但会出现在错误日志中。
¥It will not appear in the console, but it will appear in the error log.
为输出着色
¥Color the output
注意 此部分资源是使用版本 22.11 设计的,该版本将
styleText
标记为“主动开发”。¥This part of the resource is designed with version 22.11 which notes
styleText
as ‘Active development’.
在许多情况下,你会倾向于粘贴某些文本以在终端上获得不错的输出。
¥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:
import { styleText } from 'node:util';
然后,你可以使用它来设置文本样式:
¥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