使用 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'
);
第一個引數是一個樣式陣列,第二個引數是你想設定樣式的文字。我們邀請您閱讀文件