使用 Node.js 输出到命令行
使用 console 模块进行基本输出
Node.js 提供了一个 console 模块,它提供了许多与命令行交互的非常实用的方法。
它与你在浏览器中找到的 console 对象基本相同。
最基本也是最常用的方法是 console.log(),它会将你传递给它的字符串打印到控制台。
如果你传递一个对象,它会将其渲染成字符串。
你可以向 console.log 传递多个变量,例如
const = 'x';
const = 'y';
.(, );
Node.js 会将两者都打印出来。
我们还可以通过传递变量和格式说明符来格式化漂亮的短语。
例如:
.('My %s has %d ears', 'cat', 2);
%s将变量格式化为字符串%d将变量格式化为数字%i将变量格式化为其整数部分%o将变量格式化为对象
示例
.('%o', );
清除控制台
console.clear() 会清除控制台(具体行为可能取决于所使用的控制台)
元素计数
console.count() 是一个很方便的方法。
看这段代码
const = 1;
const = 2;
const = 3;
.(
'The value of x is ' + + ' and has been checked .. how many times?'
);
.(
'The value of x is ' + + ' and has been checked .. how many times?'
);
.(
'The value of y is ' + + ' and has been checked .. how many times?'
);
发生的情况是,console.count() 会计算一个字符串被打印的次数,并在其旁边打印出计数值。
你可以只计算苹果和橙子
const = ['orange', 'orange'];
const = ['just one apple'];
.( => {
.();
});
.( => {
.();
});
重置计数
console.countReset() 方法会重置与 console.count() 一起使用的计数器。
我们将使用苹果和橙子的例子来演示这一点。
const = ['orange', 'orange'];
const = ['just one apple'];
.( => {
.();
});
.( => {
.();
});
.('orange');
.( => {
.();
});
请注意,调用 console.countReset('orange') 将橙子的计数器值重置为零。
打印堆栈跟踪
在某些情况下,打印函数的调用堆栈跟踪可能很有用,也许是为了回答*你是如何到达代码的那一部分的?*这个问题。
你可以使用 console.trace() 来做到这一点
const = () => .();
const = () => ();
();
这将打印出堆栈跟踪。这是我们在 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 = () => .('test');
const = () => {
.('doSomething()');
// do something, and measure the time it takes
();
.('doSomething()');
};
();
stdout 和 stderr
正如我们所见,console.log 非常适合在控制台中打印消息。这就是所谓的标准输出,或 stdout。
console.error 会打印到 stderr 流。
它会出现在控制台中,但可以与常规输出分开处理。
为输出着色
注意 本资源的这一部分是针对 22.11 版本设计的,该版本将
styleText标记为“活跃开发中”。
在很多情况下,你会想粘贴某些文本以在终端获得漂亮的输出。
node:util 模块提供了一个 styleText 函数。让我们来了解如何使用它。
首先,你需要从 node:util 模块导入 styleText 函数
import { } from 'node:util';
然后,你可以用它来为你的文本设置样式
.(
styleText(['red'], 'This is red text ') +
styleText(['green', 'bold'], 'and this is green bold text ') +
'this is normal text'
);
第一个参数是一个样式数组,第二个参数是你想设置样式的文本。我们邀请您阅读文档