Console#

穩定度:2 - 穩定

node:console 模組提供了一個簡單的偵錯主控台,類似於網頁瀏覽器提供的 JavaScript 主控台機制。

該模組匯出了兩個特定組件

  • 一個 Console 類別,包含 console.log()console.error()console.warn() 等方法,可用於寫入任何 Node.js 串流。
  • 一個全域的 console 執行個體,設定為寫入到 process.stdoutprocess.stderr。全域 console 不需要呼叫 require('node:console') 即可使用。

警告:全域 console 物件的方法既不完全像它們所模仿的瀏覽器 API 那樣是同步的,也不完全像所有其他 Node.js 串流那樣是非同步的。想要依賴 console 函式同步/非同步行為的程式,應該先釐清 console 底層串流的性質。這是因為串流取決於底層平台以及目前程序的標準串流設定。請參閱關於程序 I/O 的說明以取得更多資訊。

使用全域 console 的範例

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

使用 Console 類別的範例

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

類別:Console#

Console 類別可用於建立具有可配置輸出串流的簡單記錄器 (logger),並可透過 require('node:console').Consoleconsole.Console(或其解構後的對應項)存取

import { Console } from 'node:console';
const { Console } = require('node:console');
const { Console } = console;

new Console(stdout[, stderr][, ignoreErrors])#

new Console(options)#

  • options <Object>
    • stdout <stream.Writable>
    • stderr <stream.Writable>
    • ignoreErrors <boolean> 寫入底層串流時忽略錯誤。 預設值: true
    • colorMode <boolean> | <string> 設定此 Console 執行個體的色彩支援。設定為 true 會在檢查值時啟用著色。設定為 false 會停用著色。設定為 'auto' 會使色彩支援取決於 isTTY 屬性的值以及各別串流上 getColorDepth() 傳回的值。如果同時設定了 inspectOptions.colors,則不能使用此選項。 預設值: 'auto'
    • inspectOptions <Object> | <Map> 指定傳遞給 util.inspect() 的選項。可以是一個選項物件,或者如果希望對 stdout 和 stderr 使用不同的選項,可以是從串流物件到選項的 Map
    • groupIndentation <number> 設定群組縮排。 預設值: 2

使用一個或兩個可寫串流執行個體建立一個新的 Consolestdout 是用來列印 log 或 info 輸出的可寫串流。stderr 用於警告或錯誤輸出。如果未提供 stderr,則 stdout 也會用於 stderr

import { createWriteStream } from 'node:fs';
import { Console } from 'node:console';
// Alternatively
// const { Console } = console;

const output = createWriteStream('./stdout.log');
const errorOutput = createWriteStream('./stderr.log');
// Custom simple logger
const logger = new Console({ stdout: output, stderr: errorOutput });
// use it like console
const count = 5;
logger.log('count: %d', count);
// In stdout.log: count 5
const fs = require('node:fs');
const { Console } = require('node:console');
// Alternatively
// const { Console } = console;

const output = fs.createWriteStream('./stdout.log');
const errorOutput = fs.createWriteStream('./stderr.log');
// Custom simple logger
const logger = new Console({ stdout: output, stderr: errorOutput });
// use it like console
const count = 5;
logger.log('count: %d', count);
// In stdout.log: count 5

全域 console 是一個特殊的 Console,其輸出會傳送到 process.stdoutprocess.stderr。它等同於呼叫

new Console({ stdout: process.stdout, stderr: process.stderr });

console.assert(value[, ...message])#

  • value <any> 測試是否為真值 (truthy) 的值。
  • ...message <any> 除了 value 之外的所有引數都用作錯誤訊息。

如果 value假值 (falsy) 或被省略,console.assert() 會寫入訊息。它僅寫入訊息,否則不影響執行。輸出內容一律以 "Assertion failed" 開頭。如果提供了 message,則使用 util.format() 對其進行格式化。

如果 value真值 (truthy),則什麼都不會發生。

console.assert(true, 'does nothing');

console.assert(false, 'Whoops %s work', 'didn\'t');
// Assertion failed: Whoops didn't work

console.assert();
// Assertion failed

console.clear()#

stdout 是 TTY 時,呼叫 console.clear() 將嘗試清除 TTY。當 stdout 不是 TTY 時,此方法不執行任何操作。

console.clear() 的具體操作可能因作業系統和終端機類型而異。對於大多數 Linux 作業系統,console.clear() 的運作方式類似於 clear 殼層 (shell) 指令。在 Windows 上,console.clear() 只會為 Node.js 二進位檔清除目前終端機檢視區中的輸出。

console.count([label])#

  • label <string> 計數器的顯示標籤。 預設值: 'default'

維護一個特定於 label 的內部計數器,並向 stdout 輸出以給定 label 呼叫 console.count() 的次數。

> console.count()
default: 1
undefined
> console.count('default')
default: 2
undefined
> console.count('abc')
abc: 1
undefined
> console.count('xyz')
xyz: 1
undefined
> console.count('abc')
abc: 2
undefined
> console.count()
default: 3
undefined
>

console.countReset([label])#

  • label <string> 計數器的顯示標籤。 預設值: 'default'

重設特定於 label 的內部計數器。

> console.count('abc');
abc: 1
undefined
> console.countReset('abc');
undefined
> console.count('abc');
abc: 1
undefined
>

console.debug(data[, ...args])#

console.debug() 函式是 console.log() 的別名。

console.dir(obj[, options])#

  • obj <any>
  • options <Object>
    • showHidden <boolean> 如果為 true,則也會顯示物件的不可列舉屬性與符號 (symbol) 屬性。 預設值: false
    • depth <number> 告知 util.inspect() 在格式化物件時遞迴多少次。這對於檢查大型複雜物件很有用。要讓它無限遞迴,請傳遞 null預設值: 2
    • colors <boolean> 如果為 true,輸出將使用 ANSI 顏色代碼設定樣式。顏色是可自訂的;請參閱自訂 util.inspect() 顏色預設值: false

obj 上使用 util.inspect() 並將產生的字串列印到 stdout。此函式會繞過 obj 上定義的任何自訂 inspect() 函式。

console.dirxml(...data)#

此方法呼叫 console.log() 並傳遞接收到的引數。此方法不會產生任何 XML 格式。

console.error([data][, ...args])#

列印到 stderr 並換行。可以傳遞多個引數,第一個引數用作主要訊息,所有額外引數用作替換值,類似於 printf(3)(引數都會傳遞給 util.format())。

const code = 5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr

如果在第一個字串中找不到格式化元素(例如 %d),則對每個引數呼叫 util.inspect() 並將產生的字串值串聯起來。有關更多資訊,請參閱 util.format()

console.group([...label])#

將後續行的縮排增加 groupIndentation 長度的空格。

如果提供了一個或多個 label,則先列印這些標籤,不增加額外的縮排。

console.groupCollapsed()#

console.group() 的別名。

console.groupEnd()#

將後續行的縮排減少 groupIndentation 長度的空格。

console.info([data][, ...args])#

console.info() 函式是 console.log() 的別名。

console.log([data][, ...args])#

列印到 stdout 並換行。可以傳遞多個引數,第一個引數用作主要訊息,所有額外引數用作替換值,類似於 printf(3)(引數都會傳遞給 util.format())。

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

有關更多資訊,請參閱 util.format()

console.table(tabularData[, properties])#

  • tabularData <any>
  • properties <string[]> 用於建構表格的替代屬性。

嘗試使用 tabularData 的屬性(或使用 properties)作為欄,tabularData 作為列來建構表格並記錄它。如果無法解析為表格格式,則回退到僅記錄引數。

// These can't be parsed as tabular data
console.table(Symbol());
// Symbol()

console.table(undefined);
// undefined

console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);
// ┌─────────┬─────┬─────┐
// │ (index) │ a   │ b   │
// ├─────────┼─────┼─────┤
// │ 0       │ 1   │ 'Y' │
// │ 1       │ 'Z' │ 2   │
// └─────────┴─────┴─────┘

console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);
// ┌─────────┬─────┐
// │ (index) │ a   │
// ├─────────┼─────┤
// │ 0       │ 1   │
// │ 1       │ 'Z' │
// └─────────┴─────┘

console.time([label])#

  • label <string> 預設值: 'default'

啟動一個計時器,可用於計算操作的持續時間。計時器由唯一的 label 識別。呼叫 console.timeEnd() 時使用相同的 label 以停止計時器,並以合適的時間單位向 stdout 輸出經過的時間。例如,如果經過時間為 3869ms,console.timeEnd() 會顯示 "3.869s"。

console.timeEnd([label])#

  • label <string> 預設值: 'default'

停止先前呼叫 console.time() 啟動的計時器,並將結果列印到 stdout

console.time('bunch-of-stuff');
// Do a bunch of stuff.
console.timeEnd('bunch-of-stuff');
// Prints: bunch-of-stuff: 225.438ms

console.timeLog([label][, ...data])#

對於先前呼叫 console.time() 啟動的計時器,將經過的時間和其他 data 引數列印到 stdout

console.time('process');
const value = expensiveProcess1(); // Returns 42
console.timeLog('process', value);
// Prints "process: 365.227ms 42".
doExpensiveProcess2(value);
console.timeEnd('process');

console.trace([message][, ...args])#

將字串 'Trace: ' 列印到 stderr,後面接著經 util.format() 格式化的訊息以及程式碼目前位置的堆疊追蹤 (stack trace)。

console.trace('Show me');
// Prints: (stack trace will vary based on where trace is called)
//  Trace: Show me
//    at repl:2:9
//    at REPLServer.defaultEval (repl.js:248:27)
//    at bound (domain.js:287:14)
//    at REPLServer.runBound [as eval] (domain.js:300:12)
//    at REPLServer.<anonymous> (repl.js:412:12)
//    at emitOne (events.js:82:20)
//    at REPLServer.emit (events.js:169:7)
//    at REPLServer.Interface._onLine (readline.js:210:10)
//    at REPLServer.Interface._line (readline.js:549:8)
//    at REPLServer.Interface._ttyWrite (readline.js:826:14)

console.warn([data][, ...args])#

console.warn() 函式是 console.error() 的別名。

僅限檢查器 (Inspector) 的方法#

以下方法是由 V8 引擎在一般 API 中公開的,但除非與檢查器 (inspector)(使用 --inspect 旗標)結合使用,否則不會顯示任何內容。

console.profile([label])#

除非在檢查器中使用,否則此方法不會顯示任何內容。console.profile() 方法會啟動一個具有選擇性標籤的 JavaScript CPU 分析檔案 (profile),直到呼叫 console.profileEnd() 為止。該分析檔案隨後會被新增到檢查器的 Profile 面板中。

console.profile('MyLabel');
// Some code
console.profileEnd('MyLabel');
// Adds the profile 'MyLabel' to the Profiles panel of the inspector.

console.profileEnd([label])#

除非在檢查器中使用,否則此方法不會顯示任何內容。如果已啟動 JavaScript CPU 分析工作階段,則停止該工作階段,並將報告列印到檢查器的 Profiles 面板。範例請參閱 console.profile()

如果呼叫此方法時沒有標籤,則停止最近啟動的分析檔案。

console.timeStamp([label])#

除非在檢查器中使用,否則此方法不會顯示任何內容。console.timeStamp() 方法會將帶有標籤 'label' 的事件新增到檢查器的 Timeline 面板中。