使用 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
你可以使用 转义序列 在控制台中为文本的输出着色。转义序列是一组用于标识颜色的字符。
¥You can color the output of your text in the console by using escape sequences. An escape sequence is a set of characters that identifies a color.
示例:
¥Example:
console.log('\x1b[33m%s\x1b[0m', 'hi!');
你可以在 Node.js REPL 中尝试,它将以黄色打印 hi!
。
¥You can try that in the Node.js REPL, and it will print hi!
in yellow.
但是,这是执行此操作的底层方法。为控制台输出着色的最简单方法是使用库。Chalk 就是这样一个库,除了着色之外,它还可以帮助实现其他样式功能,例如使文本加粗、斜体或加下划线。
¥However, this is the low-level way to do this. The simplest way to go about coloring the console output is by using a library. Chalk is such a library, and in addition to coloring it also helps with other styling facilities, like making text bold, italic or underlined.
你将其与 npm install chalk
一起安装,然后就可以使用它了:
¥You install it with npm install chalk
, then you can use it:
const chalk = require('chalk');
console.log(chalk.yellow('hi!'));
使用 chalk.yellow
比尝试记住转义码更方便,并且代码更具可读性。
¥Using chalk.yellow
is much more convenient than trying to remember the escape codes, and the code is much more readable.
查看上面发布的项目链接以获取更多使用示例。
¥Check the project link posted above for more usage examples.
创建进度条
¥Create a progress bar
进度 是一个很棒的包,可以在控制台中创建进度条。使用 npm install progress
安装
¥Progress is an awesome package to create a progress bar in the console. Install it using npm install progress
此代码段创建了一个 10 步进度条,每 100 毫秒完成一步。当柱状图完成时,我们清除间隔:
¥This snippet creates a 10-step progress bar, and every 100ms one step is completed. When the bar completes we clear the interval:
const ProgressBar = require('progress');
const bar = new ProgressBar(':bar', { total: 10 });
const timer = setInterval(() => {
bar.tick();
if (bar.complete) {
clearInterval(timer);
}
}, 100);