• Node.js Video Tutorials

Node.js - 控制檯



控制檯是一個基於文字的使用者介面,允許您與計算機的作業系統互動或執行程式碼。 使用控制檯,您可以編寫和執行命令或程式。 它也用於除錯和故障排除。 Node.js 的內建庫包含 Console 模組。它提供將訊息列印到 IO 流的功能,該功能類似於 Web 瀏覽器提供的 JavaScript 控制檯機制。

Console 模組的功能主要分為兩部分:

Console 類:Console 類的常用方法有 console.log()、console.error() 和 console.warn(),用於顯示 Node.js 流。

全域性 console 物件:一個預定義的物件,將日誌、錯誤和警告訊息回顯到標準輸出流。 使用時無需呼叫 require('console')。

全域性 console 物件的預設用法很簡單。 下面的程式碼展示了全域性 console 物件的典型用法,用於顯示日誌、錯誤和警告訊息。

示例

// Welcome message
console.log('Welcome to Tutorialspoint!');

// Hello world message

console.log('hello world');

// printing to error stream

console.error(new Error('Oops... something went wrong'));

// print warning

const name = 'NodeJS Tutorial';

console.warn(`Warning ${name}! Warning!`);

輸出

Welcome to Tutorialspoint!
hello world
Error: Oops... something went wrong
   at Object.<anonymous> (D:\nodejs\emailapp\main.js:11:15)
    at Module._compile (node:internal/modules/cjs/loader:1241:14)
	at Module._extensions..js (node:internal/modules/cjs/loader:1295:10)
    at Module.load (node:internal/modules/cjs/loader:1091:32)
    at Module._load (node:internal/modules/cjs/loader:938:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12)
    at node:internal/main/run_main_module:23:47
Warning NodeJS Tutorial! Warning!

您還可以透過指定用於反映輸出和錯誤日誌的流來自定義 console 物件。宣告 Console 類的物件並將流物件作為引數傳遞。

下面的程式將日誌和錯誤重定向到兩個磁碟檔案。

const fs = require('fs');

const out = fs.createWriteStream('./stdout.log');

const err = fs.createWriteStream('./stderr.log');

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

// Welcome message
logger.log('Welcome to Tutorialspoint!');

// Hello world message

logger.log('hello world');

// printing to error stream

logger.error(new Error('Oops... something went wrong'));

// print warning

const name = 'NodeJS Tutorial';

logger.warn(`Warning ${name}! Warning!`);

這將在當前目錄中建立兩個檔案 stdout.log 和 stderr.log,其中儲存了 console 物件的 log()、error() 和 warn() 方法的結果。

Console 方法

以下是 console 物件可用的方法列表。

序號 方法及描述
1

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

帶換行符列印到 stdout。此函式可以像 printf() 一樣接受多個引數。

2

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

帶換行符列印到 stdout。此函式可以像 printf() 一樣接受多個引數。

3

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

帶換行符列印到 stderr。此函式可以像 printf() 一樣接受多個引數。

4

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

帶換行符列印到 stderr。此函式可以像 printf() 一樣接受多個引數。

5

console.dir(obj[, options])

對 obj 使用 util.inspect 並將結果字串列印到 stdout。

6

console.time(label)

標記時間。

7

console.timeEnd(label)

結束計時器,記錄輸出。

8

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

列印到 stderr 'Trace :', 後跟格式化的訊息和到當前位置的堆疊跟蹤。

9

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

類似於 assert.ok(),但錯誤訊息格式化為 util.format(message...)。

nodejs_global_objects.htm
廣告