Node.js v21.7.2 ドキュメント
- Node.js v21.7.2
-
► 目次
- コンソール
- クラス:
Console
new Console(stdout[, stderr][, ignoreErrors])
new Console(options)
console.assert(value[, ...message])
console.clear()
console.count([label])
console.countReset([label])
console.debug(data[, ...args])
console.dir(obj[, options])
console.dirxml(...data)
console.error([data][, ...args])
console.group([...label])
console.groupCollapsed()
console.groupEnd()
console.info([data][, ...args])
console.log([data][, ...args])
console.table(tabularData[, properties])
console.time([label])
console.timeEnd([label])
console.timeLog([label][, ...data])
console.trace([message][, ...args])
console.warn([data][, ...args])
- インスペクター専用メソッド
- クラス:
- コンソール
-
► インデックス
- アサーションテスト
- 非同期コンテキスト追跡
- Async hooks
- Buffer
- C++ アドオン
- Node-API を使用した C/C++ アドオン
- C++ エンベッダー API
- 子プロセス
- Cluster
- コマンドラインオプション
- コンソール
- Corepack
- Crypto
- デバッガー
- 非推奨 API
- 診断チャネル
- DNS
- Domain
- エラー
- Events
- ファイルシステム
- グローバル
- HTTP
- HTTP/2
- HTTPS
- インスペクター
- 国際化
- モジュール: CommonJS モジュール
- モジュール: ECMAScript モジュール
- モジュール:
node:module
API - モジュール: パッケージ
- Net
- OS
- Path
- パフォーマンスフック
- パーミッション
- Process
- Punycode
- クエリストリング
- Readline
- REPL
- レポート
- 単一実行可能アプリケーション
- Stream
- 文字列デコーダー
- テストランナー
- タイマー
- TLS/SSL
- トレースイベント
- TTY
- UDP/データグラム
- URL
- ユーティリティ
- V8
- VM
- WASI
- Web Crypto API
- Web Streams API
- ワーカースレッド
- Zlib
- ► その他のバージョン
- ► オプション
コンソール#
ソースコード: lib/console.js
node:console
モジュールは、Web ブラウザが提供する JavaScript コンソールメカニズムに似た、シンプルなデバッグコンソールを提供します。
このモジュールは、2 つの特定のコンポーネントをエクスポートします。
console.log()
、console.error()
、console.warn()
などのメソッドを持つConsole
クラス。任意の Node.js ストリームへの書き込みに使用できます。process.stdout
およびprocess.stderr
に書き込むように構成されたグローバルなconsole
インスタンス。グローバルなconsole
はrequire('node:console')
を呼び出さずに使用できます。
警告: グローバルな console オブジェクトのメソッドは、それらが似ているブラウザ API のように一貫して同期するわけでも、他のすべての Node.js ストリームのように一貫して非同期するわけでもありません。詳細については、プロセス 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
クラスは、構成可能な出力ストリームを持つシンプルなロガーを作成するために使用でき、require('node:console').Console
または console.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>util.inspect()
に渡されるオプションを指定します。groupIndentation
<number> グループインデントを設定します。デフォルト:2
。
1 つまたは 2 つの書き込み可能なストリームインスタンスを持つ新しい Console
を作成します。stdout
は、ログまたは情報出力を印刷するための書き込み可能なストリームです。stderr
は、警告またはエラー出力に使用されます。stderr
が提供されない場合、stdout
が stderr
に使用されます。
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
は、出力が process.stdout
および process.stderr
に送信される特別な Console
です。これは、次のように呼び出すことと同等です。
new Console({ stdout: process.stdout, stderr: process.stderr });
console.assert(value[, ...message])
#
console.assert()
は、value
が falsy であるか、省略された場合にメッセージを書き込みます。メッセージを書き込むだけで、実行には影響しません。出力は常に "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
シェルコマンドと同様に動作します。Windows では、console.clear()
は Node.js バイナリの現在の端末ビューポートの出力のみをクリアします。
console.count([label])
#
label
<string> カウンターの表示ラベル。デフォルト:'default'
。
label
に固有の内部カウンターを保持し、指定された label
で console.count()
が呼び出された回数を stdout
に出力します。
> 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
の場合、オブジェクトの列挙不可能なシンボルプロパティも表示されます。デフォルト:false
。depth
<number> オブジェクトをフォーマットする際に、util.inspect()
を再帰させる回数を指定します。これは、複雑な大きなオブジェクトを検査する場合に役立ちます。無限に再帰させるには、null
を渡します。デフォルト:2
。colors
<boolean>true
の場合、出力は ANSI カラーコードでスタイルされます。色はカスタマイズできます。util.inspect()
の色のカスタマイズを参照してください。デフォルト:false
。
obj
で util.inspect()
を使用し、結果の文字列を stdout
に出力します。この関数は、obj
で定義されているカスタムの inspect()
関数をバイパスします。
console.dirxml(...data)
#
...data
<any>
このメソッドは、受信した引数を渡して 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])
#
...label
<any>
後続の行のインデントをgroupIndentation
の長さだけスペースで増やします。
1つ以上の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: '
に続けて、util.format()
でフォーマットされたメッセージと、コードの現在位置へのスタックトレースをstderr
に出力します。
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()
のエイリアスです。
インスペクター専用メソッド#
次のメソッドは、一般的なAPIでV8エンジンによって公開されていますが、インスペクター(--inspect
フラグ)と組み合わせて使用しない限り、何も表示されません。
console.profile([label])
#
label
<string>
このメソッドは、インスペクターで使用しない限り何も表示しません。console.profile()
メソッドは、console.profileEnd()
が呼び出されるまで、オプションのラベル付きでJavaScript CPUプロファイルを開始します。その後、プロファイルはインスペクターのプロファイルパネルに追加されます。
console.profile('MyLabel');
// Some code
console.profileEnd('MyLabel');
// Adds the profile 'MyLabel' to the Profiles panel of the inspector.
console.profileEnd([label])
#
label
<string>
このメソッドは、インスペクターで使用しない限り何も表示しません。開始されたJavaScript CPUプロファイルセッションがある場合はそれを停止し、レポートをインスペクターのプロファイルパネルに出力します。例については、console.profile()
を参照してください。
ラベルなしでこのメソッドが呼び出された場合、最後に開始されたプロファイルが停止されます。
console.timeStamp([label])
#
label
<string>
このメソッドは、インスペクターで使用しない限り何も表示しません。console.timeStamp()
メソッドは、ラベル'label'
付きのイベントをインスペクターのタイムラインパネルに追加します。