Node.js v25.0.0 ドキュメンテーション
- Node.js v25.0.0
-
目次
- Util
util.callbackify(original)util.debuglog(section[, callback])util.debug(section)util.deprecate(fn, msg[, code])util.diff(actual, expected)util.format(format[, ...args])util.formatWithOptions(inspectOptions, format[, ...args])util.getCallSites([frameCount][, options])util.getSystemErrorName(err)util.getSystemErrorMap()util.getSystemErrorMessage(err)util.setTraceSigInt(enable)util.inherits(constructor, superConstructor)util.inspect(object[, options])util.inspect(object[, showHidden[, depth[, colors]]])util.isDeepStrictEqual(val1, val2[, options])- クラス:
util.MIMEType - クラス:
util.MIMEParams util.parseArgs([config])util.parseEnv(content)util.promisify(original)util.stripVTControlCharacters(str)util.styleText(format, text[, options])- クラス:
util.TextDecoder - クラス:
util.TextEncoder util.toUSVString(string)util.transferableAbortController()util.transferableAbortSignal(signal)util.aborted(signal, resource)util.typesutil.types.isAnyArrayBuffer(value)util.types.isArrayBufferView(value)util.types.isArgumentsObject(value)util.types.isArrayBuffer(value)util.types.isAsyncFunction(value)util.types.isBigInt64Array(value)util.types.isBigIntObject(value)util.types.isBigUint64Array(value)util.types.isBooleanObject(value)util.types.isBoxedPrimitive(value)util.types.isCryptoKey(value)util.types.isDataView(value)util.types.isDate(value)util.types.isExternal(value)util.types.isFloat16Array(value)util.types.isFloat32Array(value)util.types.isFloat64Array(value)util.types.isGeneratorFunction(value)util.types.isGeneratorObject(value)util.types.isInt8Array(value)util.types.isInt16Array(value)util.types.isInt32Array(value)util.types.isKeyObject(value)util.types.isMap(value)util.types.isMapIterator(value)util.types.isModuleNamespaceObject(value)util.types.isNativeError(value)util.types.isNumberObject(value)util.types.isPromise(value)util.types.isProxy(value)util.types.isRegExp(value)util.types.isSet(value)util.types.isSetIterator(value)util.types.isSharedArrayBuffer(value)util.types.isStringObject(value)util.types.isSymbolObject(value)util.types.isTypedArray(value)util.types.isUint8Array(value)util.types.isUint8ClampedArray(value)util.types.isUint16Array(value)util.types.isUint32Array(value)util.types.isWeakMap(value)util.types.isWeakSet(value)
- 非推奨のAPI
- Util
-
索引
- アサーションテスト
- 非同期コンテキストの追跡
- Async hooks
- Buffer
- C++アドオン
- Node-API を使用した C/C++ アドオン
- C++ embedder API
- 子プロセス
- Cluster
- コマンドラインオプション
- Console
- Crypto
- Debugger
- 非推奨のAPI
- Diagnostics Channel
- DNS
- Domain
- 環境変数
- エラー
- Events
- ファイルシステム
- Globals
- HTTP
- HTTP/2
- HTTPS
- Inspector
- 国際化
- モジュール: CommonJS モジュール
- モジュール: ECMAScript モジュール
- モジュール:
node:moduleAPI - モジュール: パッケージ
- モジュール: TypeScript
- Net
- OS
- Path
- Performance hooks
- パーミッション
- Process
- Punycode
- クエリストリング
- Readline
- REPL
- レポート
- 単一実行可能ファイルアプリケーション
- SQLite
- Stream
- String decoder
- テストランナー
- タイマー
- TLS/SSL
- トレースイベント
- TTY
- UDP/datagram
- URL
- ユーティリティ
- V8
- VM
- WASI
- Web Crypto API
- Web Streams API
- ワーカースレッド
- Zlib
- 他のバージョン
- オプション
Util#
ソースコード: lib/util.js
node:util モジュールは Node.js の内部 API のニーズをサポートします。ユーティリティの多くは、アプリケーションやモジュールの開発者にとっても有用です。アクセスするには
import util from 'node:util';const util = require('node:util');
util.callbackify(original)#
original<Function>async関数- 戻り値: <Function> コールバックスタイルの関数
async 関数 (または Promise を返す関数) を受け取り、エラーファーストのコールバックスタイルに従う関数を返します。つまり、最後の引数として (err, value) => ... コールバックを取ります。コールバックでは、最初の引数はリジェクト理由 (Promise が解決された場合は null) になり、2番目の引数は解決された値になります。
import { callbackify } from 'node:util';
async function fn() {
return 'hello world';
}
const callbackFunction = callbackify(fn);
callbackFunction((err, ret) => {
if (err) throw err;
console.log(ret);
});const { callbackify } = require('node:util');
async function fn() {
return 'hello world';
}
const callbackFunction = callbackify(fn);
callbackFunction((err, ret) => {
if (err) throw err;
console.log(ret);
});
以下が出力されます
hello world
コールバックは非同期的に実行され、限定されたスタックトレースを持ちます。コールバックがスローした場合、プロセスは 'uncaughtException' イベントを発行し、処理されない場合は終了します。
null はコールバックの最初の引数として特別な意味を持つため、ラップされた関数が偽値の理由で Promise をリジェクトした場合、その値は Error にラップされ、元の値は reason というフィールドに格納されます。
function fn() {
return Promise.reject(null);
}
const callbackFunction = util.callbackify(fn);
callbackFunction((err, ret) => {
// When the Promise was rejected with `null` it is wrapped with an Error and
// the original value is stored in `reason`.
err && Object.hasOwn(err, 'reason') && err.reason === null; // true
});
util.debuglog(section[, callback])#
section<string>debuglog関数が作成されるアプリケーションの部分を識別する文字列。callback<Function> ロギング関数が初めて呼び出されたときに、より最適化されたロギング関数である関数引数とともに呼び出されるコールバック。- 戻り値: <Function> ロギング関数
util.debuglog() メソッドは、NODE_DEBUG 環境変数の存在に基づいてデバッグメッセージを条件付きで stderr に書き込む関数を作成するために使用されます。section 名がその環境変数の値内に現れる場合、返される関数は console.error() と同様に動作します。そうでない場合、返される関数は何もしません。
import { debuglog } from 'node:util';
const log = debuglog('foo');
log('hello from foo [%d]', 123);const { debuglog } = require('node:util');
const log = debuglog('foo');
log('hello from foo [%d]', 123);
このプログラムが環境変数に NODE_DEBUG=foo を設定して実行されると、次のようなものが出力されます
FOO 3245: hello from foo [123]
ここで 3245 はプロセス ID です。その環境変数が設定されずに実行された場合、何も出力されません。
section はワイルドカードもサポートしています
import { debuglog } from 'node:util';
const log = debuglog('foo');
log('hi there, it\'s foo-bar [%d]', 2333);const { debuglog } = require('node:util');
const log = debuglog('foo');
log('hi there, it\'s foo-bar [%d]', 2333);
環境変数に NODE_DEBUG=foo* を設定して実行されると、次のようなものが出力されます
FOO-BAR 3257: hi there, it's foo-bar [2333]
NODE_DEBUG 環境変数には、カンマ区切りで複数の section 名を指定できます: NODE_DEBUG=fs,net,tls。
オプションの callback 引数を使用して、ロギング関数を初期化や不要なラッピングのない別の関数に置き換えることができます。
import { debuglog } from 'node:util';
let log = debuglog('internals', (debug) => {
// Replace with a logging function that optimizes out
// testing if the section is enabled
log = debug;
});const { debuglog } = require('node:util');
let log = debuglog('internals', (debug) => {
// Replace with a logging function that optimizes out
// testing if the section is enabled
log = debug;
});
debuglog().enabled#
- 型: <boolean>
util.debuglog().enabled ゲッターは、NODE_DEBUG 環境変数の存在に基づいて条件で使用できるテストを作成するために使用されます。section 名がその環境変数の値内に現れる場合、返される値は true になります。そうでない場合、返される値は false です。
import { debuglog } from 'node:util';
const enabled = debuglog('foo').enabled;
if (enabled) {
console.log('hello from foo [%d]', 123);
}const { debuglog } = require('node:util');
const enabled = debuglog('foo').enabled;
if (enabled) {
console.log('hello from foo [%d]', 123);
}
このプログラムが環境変数に NODE_DEBUG=foo を設定して実行されると、次のようなものが出力されます
hello from foo [123]
util.debug(section)#
util.debuglog のエイリアスです。util.debuglog().enabled のみを使用する場合、ロギングを意味しない可読性を許容します。
util.deprecate(fn, msg[, code])#
fn<Function> 非推奨とされる関数。msg<string> 非推奨の関数が呼び出されたときに表示される警告メッセージ。code<string> 非推奨コード。コードのリストについては、非推奨 API のリスト を参照してください。- 戻り値: <Function> 警告を発行するようにラップされた非推奨の関数。
util.deprecate() メソッドは、fn (関数またはクラス) を非推奨としてマークされるようにラップします。
import { deprecate } from 'node:util';
export const obsoleteFunction = deprecate(() => {
// Do something here.
}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');const { deprecate } = require('node:util');
exports.obsoleteFunction = deprecate(() => {
// Do something here.
}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');
呼び出されると、util.deprecate() は 'warning' イベントを使用して DeprecationWarning を発行する関数を返します。警告は、返された関数が初めて呼び出されたときに stderr に発行され、表示されます。警告が発行された後、ラップされた関数は警告を発行せずに呼び出されます。
複数の util.deprecate() 呼び出しで同じオプションの code が提供された場合、警告はその code に対して一度だけ発行されます。
import { deprecate } from 'node:util';
const fn1 = deprecate(
() => 'a value',
'deprecation message',
'DEP0001',
);
const fn2 = deprecate(
() => 'a different value',
'other dep message',
'DEP0001',
);
fn1(); // Emits a deprecation warning with code DEP0001
fn2(); // Does not emit a deprecation warning because it has the same codeconst { deprecate } = require('node:util');
const fn1 = deprecate(
function() {
return 'a value';
},
'deprecation message',
'DEP0001',
);
const fn2 = deprecate(
function() {
return 'a different value';
},
'other dep message',
'DEP0001',
);
fn1(); // Emits a deprecation warning with code DEP0001
fn2(); // Does not emit a deprecation warning because it has the same code
--no-deprecation または --no-warnings コマンドラインフラグが使用されている場合、または process.noDeprecation プロパティが最初の非推奨警告の *前に* true に設定されている場合、util.deprecate() メソッドは何もしません。
--trace-deprecation または --trace-warnings コマンドラインフラグが設定されている場合、または process.traceDeprecation プロパティが true に設定されている場合、非推奨の関数が初めて呼び出されたときに警告とスタックトレースが stderr に表示されます。
--throw-deprecation コマンドラインフラグが設定されている場合、または process.throwDeprecation プロパティが true に設定されている場合、非推奨の関数が呼び出されると例外がスローされます。
--throw-deprecation コマンドラインフラグと process.throwDeprecation プロパティは、--trace-deprecation と process.traceDeprecation よりも優先されます。
util.diff(actual, expected)#
-
戻り値: <Array> 差分エントリの配列。各エントリは2つの要素を持つ配列です
-
アルゴリズムの複雑さ: O(N*D)、ここで
-
N は2つのシーケンスの合計長 (N = actual.length + expected.length)
-
D は編集距離 (一方のシーケンスを他方に変換するために必要な最小操作数)。
util.diff() は2つの文字列または配列の値を比較し、差分エントリの配列を返します。これは、アサーションエラーメッセージで内部的に使用されるのと同じアルゴリズムである Myers 差分アルゴリズムを使用して最小差分を計算します。
値が等しい場合、空の配列が返されます。
const { diff } = require('node:util');
// Comparing strings
const actualString = '12345678';
const expectedString = '12!!5!7!';
console.log(diff(actualString, expectedString));
// [
// [0, '1'],
// [0, '2'],
// [1, '3'],
// [1, '4'],
// [-1, '!'],
// [-1, '!'],
// [0, '5'],
// [1, '6'],
// [-1, '!'],
// [0, '7'],
// [1, '8'],
// [-1, '!'],
// ]
// Comparing arrays
const actualArray = ['1', '2', '3'];
const expectedArray = ['1', '3', '4'];
console.log(diff(actualArray, expectedArray));
// [
// [0, '1'],
// [1, '2'],
// [0, '3'],
// [-1, '4'],
// ]
// Equal values return empty array
console.log(diff('same', 'same'));
// []
util.format(format[, ...args])#
format<string>printfのようなフォーマット文字列。
util.format() メソッドは、最初の引数を printf のようなフォーマット文字列として使用してフォーマットされた文字列を返します。このフォーマット文字列には、0個以上のフォーマット指定子を含めることができます。各指定子は、対応する引数から変換された値に置き換えられます。サポートされている指定子は次のとおりです。
%s:BigInt、Object、-0を除くすべての値を変換するためにStringが使用されます。BigIntの値はnで表され、ユーザー定義のtoString関数もSymbol.toPrimitive関数も持たないオブジェクトは、{ depth: 0, colors: false, compact: 3 }オプションでutil.inspect()を使用して検査されます。%d:BigIntとSymbolを除くすべての値を変換するためにNumberが使用されます。%i:BigIntとSymbolを除くすべての値に対してparseInt(value, 10)が使用されます。%f:Symbolを除くすべての値に対してparseFloat(value)が使用されます。%j: JSON。引数に循環参照が含まれている場合は、文字列'[Circular]'に置き換えられます。%o:Object。汎用的な JavaScript オブジェクトフォーマットのオブジェクトの文字列表現。{ showHidden: true, showProxy: true }オプションを持つutil.inspect()に似ています。これにより、列挙不可能なプロパティやプロキシを含む完全なオブジェクトが表示されます。%O:Object。汎用的な JavaScript オブジェクトフォーマットのオブジェクトの文字列表現。オプションなしのutil.inspect()に似ています。これにより、列挙不可能なプロパティやプロキシを含まない完全なオブジェクトが表示されます。%c:CSS。この指定子は無視され、渡された CSS はスキップされます。%%: 単一のパーセント記号 ('%')。これは引数を消費しません。- 戻り値: <string> フォーマットされた文字列
指定子に対応する引数がない場合、それは置き換えられません。
util.format('%s:%s', 'foo');
// Returns: 'foo:%s'
フォーマット文字列の一部ではない値は、その型が string でない場合、util.inspect() を使用してフォーマットされます。
util.format() メソッドに指定子の数よりも多くの引数が渡された場合、余分な引数はスペースで区切られて返される文字列に連結されます。
util.format('%s:%s', 'foo', 'bar', 'baz');
// Returns: 'foo:bar baz'
最初の引数に有効なフォーマット指定子が含まれていない場合、util.format() はすべての引数をスペースで区切って連結した文字列を返します。
util.format(1, 2, 3);
// Returns: '1 2 3'
util.format() に引数が1つだけ渡された場合、それはフォーマットされずにそのまま返されます。
util.format('%% %s');
// Returns: '%% %s'
util.format() はデバッグツールとして意図された同期メソッドです。一部の入力値は、イベントループをブロックする可能性のある重大なパフォーマンスオーバーヘッドを持つことがあります。この関数は注意して使用し、ホットコードパスでは決して使用しないでください。
util.formatWithOptions(inspectOptions, format[, ...args])#
この関数は util.format() と同じですが、util.inspect() に渡されるオプションを指定する inspectOptions 引数を取る点が異なります。
util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 });
// Returns 'See object { foo: 42 }', where `42` is colored as a number
// when printed to a terminal.
util.getCallSites([frameCount][, options])#
frameCount<number> コールサイトオブジェクトとしてキャプチャするフレームのオプション数。デフォルト:10。許容範囲は 1 から 200 です。options<Object> オプションsourceMap<boolean> ソースマップからスタックトレースの元の位置を再構築します。--enable-source-mapsフラグでデフォルトで有効になります。
- 戻り値: <Object[]> コールサイトオブジェクトの配列
呼び出し元関数のスタックを含むコールサイトオブジェクトの配列を返します。
import { getCallSites } from 'node:util';
function exampleFunction() {
const callSites = getCallSites();
console.log('Call Sites:');
callSites.forEach((callSite, index) => {
console.log(`CallSite ${index + 1}:`);
console.log(`Function Name: ${callSite.functionName}`);
console.log(`Script Name: ${callSite.scriptName}`);
console.log(`Line Number: ${callSite.lineNumber}`);
console.log(`Column Number: ${callSite.column}`);
});
// CallSite 1:
// Function Name: exampleFunction
// Script Name: /home/example.js
// Line Number: 5
// Column Number: 26
// CallSite 2:
// Function Name: anotherFunction
// Script Name: /home/example.js
// Line Number: 22
// Column Number: 3
// ...
}
// A function to simulate another stack layer
function anotherFunction() {
exampleFunction();
}
anotherFunction();const { getCallSites } = require('node:util');
function exampleFunction() {
const callSites = getCallSites();
console.log('Call Sites:');
callSites.forEach((callSite, index) => {
console.log(`CallSite ${index + 1}:`);
console.log(`Function Name: ${callSite.functionName}`);
console.log(`Script Name: ${callSite.scriptName}`);
console.log(`Line Number: ${callSite.lineNumber}`);
console.log(`Column Number: ${callSite.column}`);
});
// CallSite 1:
// Function Name: exampleFunction
// Script Name: /home/example.js
// Line Number: 5
// Column Number: 26
// CallSite 2:
// Function Name: anotherFunction
// Script Name: /home/example.js
// Line Number: 22
// Column Number: 3
// ...
}
// A function to simulate another stack layer
function anotherFunction() {
exampleFunction();
}
anotherFunction();
オプション sourceMap を true に設定することで、元の位置を再構築することが可能です。ソースマップが利用できない場合、元の位置は現在の位置と同じになります。--experimental-transform-types を使用する場合など、--enable-source-maps フラグが有効になっている場合、sourceMap はデフォルトで true になります。
import { getCallSites } from 'node:util';
interface Foo {
foo: string;
}
const callSites = getCallSites({ sourceMap: true });
// With sourceMap:
// Function Name: ''
// Script Name: example.js
// Line Number: 7
// Column Number: 26
// Without sourceMap:
// Function Name: ''
// Script Name: example.js
// Line Number: 2
// Column Number: 26
const { getCallSites } = require('node:util');
const callSites = getCallSites({ sourceMap: true });
// With sourceMap:
// Function Name: ''
// Script Name: example.js
// Line Number: 7
// Column Number: 26
// Without sourceMap:
// Function Name: ''
// Script Name: example.js
// Line Number: 2
// Column Number: 26
util.getSystemErrorName(err)#
Node.js API から得られる数値エラーコードの文字列表現を返します。エラーコードとエラー名のマッピングはプラットフォームに依存します。一般的なエラーの名前については、一般的なシステムエラー を参照してください。
fs.access('file/that/does/not/exist', (err) => {
const name = util.getSystemErrorName(err.errno);
console.error(name); // ENOENT
});
util.getSystemErrorMap()#
- 戻り値: <Map>
Node.js APIから利用可能なすべてのシステムエラーコードのMapを返します。エラーコードとエラー名のマッピングはプラットフォームに依存します。一般的なエラーの名前については、一般的なシステムエラーを参照してください。
fs.access('file/that/does/not/exist', (err) => {
const errorMap = util.getSystemErrorMap();
const name = errorMap.get(err.errno);
console.error(name); // ENOENT
});
util.getSystemErrorMessage(err)#
Node.js APIから得られる数値エラーコードの文字列メッセージを返します。エラーコードと文字列メッセージのマッピングはプラットフォームに依存します。
fs.access('file/that/does/not/exist', (err) => {
const message = util.getSystemErrorMessage(err.errno);
console.error(message); // No such file or directory
});
util.setTraceSigInt(enable)#
enable<boolean>
SIGINT時にスタックトレースを出力するかどうかを有効または無効にします。このAPIはメインスレッドでのみ利用可能です。
util.inherits(constructor, superConstructor)#
extends キーワードを使用してください。constructor<Function>superConstructor<Function>
util.inherits() の使用は非推奨です。言語レベルの継承サポートを得るために、ES6 の class と extends キーワードを使用してください。また、これら2つのスタイルは意味的に互換性がないことにも注意してください。
あるコンストラクタから別のコンストラクタへプロトタイプメソッドを継承します。constructor のプロトタイプは、superConstructor から作成された新しいオブジェクトに設定されます。
これは主に Object.setPrototypeOf(constructor.prototype, superConstructor.prototype) にいくつかの入力検証を追加します。追加の便宜として、superConstructor は constructor.super_ プロパティを通じてアクセス可能になります。
const util = require('node:util');
const EventEmitter = require('node:events');
function MyStream() {
EventEmitter.call(this);
}
util.inherits(MyStream, EventEmitter);
MyStream.prototype.write = function(data) {
this.emit('data', data);
};
const stream = new MyStream();
console.log(stream instanceof EventEmitter); // true
console.log(MyStream.super_ === EventEmitter); // true
stream.on('data', (data) => {
console.log(`Received data: "${data}"`);
});
stream.write('It works!'); // Received data: "It works!"
class と extends を使用した ES6 の例
import EventEmitter from 'node:events';
class MyStream extends EventEmitter {
write(data) {
this.emit('data', data);
}
}
const stream = new MyStream();
stream.on('data', (data) => {
console.log(`Received data: "${data}"`);
});
stream.write('With ES6');const EventEmitter = require('node:events');
class MyStream extends EventEmitter {
write(data) {
this.emit('data', data);
}
}
const stream = new MyStream();
stream.on('data', (data) => {
console.log(`Received data: "${data}"`);
});
stream.write('With ES6');
util.inspect(object[, options])#
util.inspect(object[, showHidden[, depth[, colors]]])
object<any> 任意の JavaScript プリミティブまたはObject。options<Object>showHidden<boolean>trueの場合、objectの列挙不可能なシンボルとプロパティがフォーマットされた結果に含まれます。<WeakMap> と <WeakSet> のエントリも、ユーザー定義のプロトタイププロパティ(メソッドプロパティを除く)と同様に含まれます。デフォルト:false。depth<number>objectをフォーマットする際に再帰する回数を指定します。これは大きなオブジェクトを検査するのに便利です。最大コールスタックサイズまで再帰するには、Infinityまたはnullを渡します。デフォルト:2。colors<boolean>trueの場合、出力は ANSI カラーコードでスタイル設定されます。色はカスタマイズ可能です。util.inspectの色のカスタマイズを参照してください。デフォルト:false。customInspect<boolean>falseの場合、[util.inspect.custom](depth, opts, inspect)関数は呼び出されません。デフォルト:true。showProxy<boolean>trueの場合、Proxyのインスペクションにはtargetとhandlerオブジェクトが含まれます。デフォルト:false。maxArrayLength<integer> フォーマット時に含めるArray, <TypedArray>, <Map>, <WeakMap>, および <WeakSet> の要素の最大数を指定します。すべての要素を表示するにはnullまたはInfinityに設定します。要素を表示しないようにするには0または負の数に設定します。デフォルト:100。maxStringLength<integer> フォーマット時に含める最大文字数を指定します。すべての要素を表示するにはnullまたはInfinityに設定します。文字を表示しないようにするには0または負の数に設定します。デフォルト:10000。breakLength<integer> 入力値が複数行に分割される長さ。入力を単一行としてフォーマットするにはInfinityに設定します(compactをtrueまたは1以上の数値に設定した場合と組み合わせて)。デフォルト:80。compact<boolean> | <integer> これをfalseに設定すると、各オブジェクトキーが新しい行に表示されます。breakLengthより長いテキストでは改行されます。数値に設定すると、すべてのプロパティがbreakLengthに収まる限り、最も内側のn個の要素が単一行にまとめられます。短い配列要素も一緒にグループ化されます。詳細については、以下の例を参照してください。デフォルト:3。sorted<boolean> | <Function>trueまたは関数に設定すると、オブジェクトのすべてのプロパティ、およびSetとMapのエントリが結果の文字列内でソートされます。trueに設定すると、デフォルトのソートが使用されます。関数に設定すると、それは比較関数として使用されます。getters<boolean> | <string>trueに設定すると、ゲッターが検査されます。'get'に設定すると、対応するセッターがないゲッターのみが検査されます。'set'に設定すると、対応するセッターがあるゲッターのみが検査されます。これはゲッター関数によっては副作用を引き起こす可能性があります。デフォルト:false。numericSeparator<boolean>trueに設定すると、すべての bigint と数値で3桁ごとにアンダースコアが使用されます。デフォルト:false。
- 戻り値: <string>
objectの表現。
util.inspect() メソッドは、デバッグを目的とした object の文字列表現を返します。util.inspect の出力はいつでも変更される可能性があり、プログラム的に依存すべきではありません。結果を変更する追加の options を渡すことができます。util.inspect() は、コンストラクタの名前や Symbol.toStringTag プロパティを使用して、検査された値の識別可能なタグを作成します。
class Foo {
get [Symbol.toStringTag]() {
return 'bar';
}
}
class Bar {}
const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });
util.inspect(new Foo()); // 'Foo [bar] {}'
util.inspect(new Bar()); // 'Bar {}'
util.inspect(baz); // '[foo] {}'
循環参照は、参照インデックスを使用してアンカーを指します
import { inspect } from 'node:util';
const obj = {};
obj.a = [obj];
obj.b = {};
obj.b.inner = obj.b;
obj.b.obj = obj;
console.log(inspect(obj));
// <ref *1> {
// a: [ [Circular *1] ],
// b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }
// }const { inspect } = require('node:util');
const obj = {};
obj.a = [obj];
obj.b = {};
obj.b.inner = obj.b;
obj.b.obj = obj;
console.log(inspect(obj));
// <ref *1> {
// a: [ [Circular *1] ],
// b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }
// }
次の例は、util オブジェクトのすべてのプロパティを検査します
import util from 'node:util';
console.log(util.inspect(util, { showHidden: true, depth: null }));const util = require('node:util');
console.log(util.inspect(util, { showHidden: true, depth: null }));
次の例は、compact オプションの効果を強調しています
import { inspect } from 'node:util';
const o = {
a: [1, 2, [[
'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' +
'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.',
'test',
'foo']], 4],
b: new Map([['za', 1], ['zb', 'test']]),
};
console.log(inspect(o, { compact: true, depth: 5, breakLength: 80 }));
// { a:
// [ 1,
// 2,
// [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line
// 'test',
// 'foo' ] ],
// 4 ],
// b: Map(2) { 'za' => 1, 'zb' => 'test' } }
// Setting `compact` to false or an integer creates more reader friendly output.
console.log(inspect(o, { compact: false, depth: 5, breakLength: 80 }));
// {
// a: [
// 1,
// 2,
// [
// [
// 'Lorem ipsum dolor sit amet,\n' +
// 'consectetur adipiscing elit, sed do eiusmod \n' +
// 'tempor incididunt ut labore et dolore magna aliqua.',
// 'test',
// 'foo'
// ]
// ],
// 4
// ],
// b: Map(2) {
// 'za' => 1,
// 'zb' => 'test'
// }
// }
// Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a
// single line.const { inspect } = require('node:util');
const o = {
a: [1, 2, [[
'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' +
'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.',
'test',
'foo']], 4],
b: new Map([['za', 1], ['zb', 'test']]),
};
console.log(inspect(o, { compact: true, depth: 5, breakLength: 80 }));
// { a:
// [ 1,
// 2,
// [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line
// 'test',
// 'foo' ] ],
// 4 ],
// b: Map(2) { 'za' => 1, 'zb' => 'test' } }
// Setting `compact` to false or an integer creates more reader friendly output.
console.log(inspect(o, { compact: false, depth: 5, breakLength: 80 }));
// {
// a: [
// 1,
// 2,
// [
// [
// 'Lorem ipsum dolor sit amet,\n' +
// 'consectetur adipiscing elit, sed do eiusmod \n' +
// 'tempor incididunt ut labore et dolore magna aliqua.',
// 'test',
// 'foo'
// ]
// ],
// 4
// ],
// b: Map(2) {
// 'za' => 1,
// 'zb' => 'test'
// }
// }
// Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a
// single line.
showHidden オプションを使用すると、<WeakMap> および <WeakSet> のエントリを検査できます。maxArrayLength よりも多くのエントリがある場合、どのエントリが表示されるかは保証されません。つまり、同じ <WeakSet> のエントリを2回取得すると、異なる出力になる可能性があります。さらに、強い参照が残っていないエントリは、いつでもガベージコレクションされる可能性があります。
import { inspect } from 'node:util';
const obj = { a: 1 };
const obj2 = { b: 2 };
const weakSet = new WeakSet([obj, obj2]);
console.log(inspect(weakSet, { showHidden: true }));
// WeakSet { { a: 1 }, { b: 2 } }const { inspect } = require('node:util');
const obj = { a: 1 };
const obj2 = { b: 2 };
const weakSet = new WeakSet([obj, obj2]);
console.log(inspect(weakSet, { showHidden: true }));
// WeakSet { { a: 1 }, { b: 2 } }
sorted オプションは、オブジェクトのプロパティ挿入順序が util.inspect() の結果に影響を与えないことを保証します。
import { inspect } from 'node:util';
import assert from 'node:assert';
const o1 = {
b: [2, 3, 1],
a: '`a` comes before `b`',
c: new Set([2, 3, 1]),
};
console.log(inspect(o1, { sorted: true }));
// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } }
console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));
// { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }
const o2 = {
c: new Set([2, 1, 3]),
a: '`a` comes before `b`',
b: [2, 3, 1],
};
assert.strict.equal(
inspect(o1, { sorted: true }),
inspect(o2, { sorted: true }),
);const { inspect } = require('node:util');
const assert = require('node:assert');
const o1 = {
b: [2, 3, 1],
a: '`a` comes before `b`',
c: new Set([2, 3, 1]),
};
console.log(inspect(o1, { sorted: true }));
// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } }
console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));
// { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }
const o2 = {
c: new Set([2, 1, 3]),
a: '`a` comes before `b`',
b: [2, 3, 1],
};
assert.strict.equal(
inspect(o1, { sorted: true }),
inspect(o2, { sorted: true }),
);
numericSeparator オプションは、すべての数値に3桁ごとにアンダースコアを追加します。
import { inspect } from 'node:util';
const thousand = 1000;
const million = 1000000;
const bigNumber = 123456789n;
const bigDecimal = 1234.12345;
console.log(inspect(thousand, { numericSeparator: true }));
// 1_000
console.log(inspect(million, { numericSeparator: true }));
// 1_000_000
console.log(inspect(bigNumber, { numericSeparator: true }));
// 123_456_789n
console.log(inspect(bigDecimal, { numericSeparator: true }));
// 1_234.123_45const { inspect } = require('node:util');
const thousand = 1000;
const million = 1000000;
const bigNumber = 123456789n;
const bigDecimal = 1234.12345;
console.log(inspect(thousand, { numericSeparator: true }));
// 1_000
console.log(inspect(million, { numericSeparator: true }));
// 1_000_000
console.log(inspect(bigNumber, { numericSeparator: true }));
// 123_456_789n
console.log(inspect(bigDecimal, { numericSeparator: true }));
// 1_234.123_45
util.inspect() はデバッグを目的とした同期メソッドです。最大出力長は約 128 MiB です。より長い出力になる入力は切り捨てられます。
util.inspect の色のカスタマイズ#
util.inspect のカラー出力(有効な場合)は、util.inspect.styles と util.inspect.colors プロパティを通じてグローバルにカスタマイズ可能です。
util.inspect.styles は、スタイル名を util.inspect.colors の色に関連付けるマップです。
デフォルトのスタイルと関連する色は次のとおりです
bigint:yellowboolean:yellowdate:magentamodule:underlinename: (スタイルなし)null:boldnumber:yellowregexp: 文字クラス、グループ、アサーション、その他の部分を色付けして読みやすさを向上させるメソッド。色付けをカスタマイズするには、colorsプロパティを変更します。デフォルトでは['red', 'green', 'yellow', 'cyan', 'magenta']に設定されており、必要に応じて調整できます。配列は「深さ」に応じて繰り返し使用されます。special:cyan(例:Proxies)string:greensymbol:greenundefined:grey
色のスタイリングには、すべてのターミナルでサポートされているとは限らないANSI制御コードが使用されます。色のサポートを確認するには tty.hasColors() を使用してください。
事前定義された制御コードは以下にリストされています(「修飾子」、「前景色」、「背景色」としてグループ化されています)。
複雑なカスタムカラーリング#
メソッドをスタイルとして定義することが可能です。これは入力の文字列化された値を受け取ります。これは、カラーリングがアクティブで、その型が検査される場合に呼び出されます。
例: util.inspect.styles.regexp(value)
修飾子#
修飾子のサポートはターミナルによって異なります。サポートされていない場合、ほとんどは無視されます。
reset- すべての(色)修飾子をデフォルトにリセットします- bold - テキストを太字にします
- italic - テキストを斜体にします
- underline - テキストに下線を引きます
strikethrough- テキストの中央に水平線を引きます(エイリアス:strikeThrough,crossedout,crossedOut)hidden- テキストを出力しますが、見えなくします(エイリアス: conceal)- dim - 色の強度を下げます(エイリアス:
faint) - overlined - テキストに上線を引きます
- blink - テキストを一定間隔で表示・非表示にします
- inverse - 前景色と背景色を入れ替えます(エイリアス:
swapcolors,swapColors) - doubleunderline - テキストに二重下線を引きます(エイリアス:
doubleUnderline) - framed - テキストの周りに枠を描画します
前景色#
blackredgreenyellowbluemagentacyanwhitegray(エイリアス:grey,blackBright)redBrightgreenBrightyellowBrightblueBrightmagentaBrightcyanBrightwhiteBright
背景色#
bgBlackbgRedbgGreenbgYellowbgBluebgMagentabgCyanbgWhitebgGray(エイリアス:bgGrey,bgBlackBright)bgRedBrightbgGreenBrightbgYellowBrightbgBlueBrightbgMagentaBrightbgCyanBrightbgWhiteBright
オブジェクト上のカスタムインスペクション関数#
オブジェクトは、独自の [util.inspect.custom](depth, opts, inspect) 関数を定義することもできます。util.inspect() はオブジェクトを検査する際にこの関数を呼び出し、その結果を使用します。
import { inspect } from 'node:util';
class Box {
constructor(value) {
this.value = value;
}
[inspect.custom](depth, options, inspect) {
if (depth < 0) {
return options.stylize('[Box]', 'special');
}
const newOptions = Object.assign({}, options, {
depth: options.depth === null ? null : options.depth - 1,
});
// Five space padding because that's the size of "Box< ".
const padding = ' '.repeat(5);
const inner = inspect(this.value, newOptions)
.replace(/\n/g, `\n${padding}`);
return `${options.stylize('Box', 'special')}< ${inner} >`;
}
}
const box = new Box(true);
console.log(inspect(box));
// "Box< true >"const { inspect } = require('node:util');
class Box {
constructor(value) {
this.value = value;
}
[inspect.custom](depth, options, inspect) {
if (depth < 0) {
return options.stylize('[Box]', 'special');
}
const newOptions = Object.assign({}, options, {
depth: options.depth === null ? null : options.depth - 1,
});
// Five space padding because that's the size of "Box< ".
const padding = ' '.repeat(5);
const inner = inspect(this.value, newOptions)
.replace(/\n/g, `\n${padding}`);
return `${options.stylize('Box', 'special')}< ${inner} >`;
}
}
const box = new Box(true);
console.log(inspect(box));
// "Box< true >"
カスタム [util.inspect.custom](depth, opts, inspect) 関数は通常、文字列を返しますが、util.inspect() によって適切にフォーマットされる任意の型の値を返すこともできます。
import { inspect } from 'node:util';
const obj = { foo: 'this will not show up in the inspect() output' };
obj[inspect.custom] = (depth) => {
return { bar: 'baz' };
};
console.log(inspect(obj));
// "{ bar: 'baz' }"const { inspect } = require('node:util');
const obj = { foo: 'this will not show up in the inspect() output' };
obj[inspect.custom] = (depth) => {
return { bar: 'baz' };
};
console.log(inspect(obj));
// "{ bar: 'baz' }"
util.inspect.custom#
- 型: <symbol> カスタムインスペクト関数を宣言するために使用できるシンボル。
util.inspect.custom を通じてアクセスできることに加えて、このシンボルはグローバルに登録されており、どの環境でも Symbol.for('nodejs.util.inspect.custom')としてアクセスできます。
これを使用することで、Node.js 環境ではカスタムインスペクト関数が使用され、ブラウザでは無視されるような、移植性の高いコードを書くことができます。util.inspect() 関数自体は、さらなる移植性を可能にするために、カスタムインスペクト関数の3番目の引数として渡されます。
const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom');
class Password {
constructor(value) {
this.value = value;
}
toString() {
return 'xxxxxxxx';
}
[customInspectSymbol](depth, inspectOptions, inspect) {
return `Password <${this.toString()}>`;
}
}
const password = new Password('r0sebud');
console.log(password);
// Prints Password <xxxxxxxx>
オブジェクト上のカスタムインスペクション関数で詳細をご覧ください。
util.inspect.defaultOptions#
defaultOptions の値は、util.inspect が使用するデフォルトオプションのカスタマイズを可能にします。これは、console.log や util.format のように暗黙的に util.inspect を呼び出す関数に便利です。これは、1つ以上の有効な util.inspect() オプションを含むオブジェクトに設定する必要があります。オプションプロパティを直接設定することもサポートされています。
import { inspect } from 'node:util';
const arr = Array(156).fill(0);
console.log(arr); // Logs the truncated array
inspect.defaultOptions.maxArrayLength = null;
console.log(arr); // logs the full arrayconst { inspect } = require('node:util');
const arr = Array(156).fill(0);
console.log(arr); // Logs the truncated array
inspect.defaultOptions.maxArrayLength = null;
console.log(arr); // logs the full array
util.isDeepStrictEqual(val1, val2[, options])#
val1<any>val2<any>skipPrototype<boolean>trueの場合、厳密な深い等価性チェック中にプロトタイプとコンストラクタの比較がスキップされます。デフォルト:false。- 戻り値: <boolean>
val1 と val2 の間に厳密な深い等価性がある場合は true を返します。それ以外の場合は false を返します。
デフォルトでは、厳密な深い等価性にはオブジェクトのプロトタイプとコンストラクタの比較が含まれます。skipPrototype が true の場合、列挙可能なプロパティが厳密に深い等価であれば、異なるプロトタイプやコンストラクタを持つオブジェクトも等しいと見なされることがあります。
const util = require('node:util');
class Foo {
constructor(a) {
this.a = a;
}
}
class Bar {
constructor(a) {
this.a = a;
}
}
const foo = new Foo(1);
const bar = new Bar(1);
// Different constructors, same properties
console.log(util.isDeepStrictEqual(foo, bar));
// false
console.log(util.isDeepStrictEqual(foo, bar, true));
// true
厳密な深い等価性の詳細については、assert.deepStrictEqual() を参照してください。
クラス: util.MIMEType#
MIMEType クラスの実装です。
ブラウザの慣習に従い、MIMEType オブジェクトのすべてのプロパティは、オブジェクト自体のデータプロパティとしてではなく、クラスプロトタイプのゲッターおよびセッターとして実装されています。
MIME 文字列は、複数の意味のあるコンポーネントを含む構造化された文字列です。解析されると、これらの各コンポーネントのプロパティを含む MIMEType オブジェクトが返されます。
new MIMEType(input)#
input<string> 解析する入力 MIME
input を解析して新しい MIMEType オブジェクトを作成します。
import { MIMEType } from 'node:util';
const myMIME = new MIMEType('text/plain');const { MIMEType } = require('node:util');
const myMIME = new MIMEType('text/plain');
input が有効な MIME でない場合、TypeError がスローされます。与えられた値を文字列に強制的に変換しようとすることに注意してください。例えば
import { MIMEType } from 'node:util';
const myMIME = new MIMEType({ toString: () => 'text/plain' });
console.log(String(myMIME));
// Prints: text/plainconst { MIMEType } = require('node:util');
const myMIME = new MIMEType({ toString: () => 'text/plain' });
console.log(String(myMIME));
// Prints: text/plain
mime.type#
- 型: <string>
MIME のタイプ部分を取得および設定します。
import { MIMEType } from 'node:util';
const myMIME = new MIMEType('text/javascript');
console.log(myMIME.type);
// Prints: text
myMIME.type = 'application';
console.log(myMIME.type);
// Prints: application
console.log(String(myMIME));
// Prints: application/javascriptconst { MIMEType } = require('node:util');
const myMIME = new MIMEType('text/javascript');
console.log(myMIME.type);
// Prints: text
myMIME.type = 'application';
console.log(myMIME.type);
// Prints: application
console.log(String(myMIME));
// Prints: application/javascript
mime.subtype#
- 型: <string>
MIME のサブタイプ部分を取得および設定します。
import { MIMEType } from 'node:util';
const myMIME = new MIMEType('text/ecmascript');
console.log(myMIME.subtype);
// Prints: ecmascript
myMIME.subtype = 'javascript';
console.log(myMIME.subtype);
// Prints: javascript
console.log(String(myMIME));
// Prints: text/javascriptconst { MIMEType } = require('node:util');
const myMIME = new MIMEType('text/ecmascript');
console.log(myMIME.subtype);
// Prints: ecmascript
myMIME.subtype = 'javascript';
console.log(myMIME.subtype);
// Prints: javascript
console.log(String(myMIME));
// Prints: text/javascript
mime.essence#
- 型: <string>
MIME のエッセンスを取得します。このプロパティは読み取り専用です。MIME を変更するには mime.type または mime.subtype を使用してください。
import { MIMEType } from 'node:util';
const myMIME = new MIMEType('text/javascript;key=value');
console.log(myMIME.essence);
// Prints: text/javascript
myMIME.type = 'application';
console.log(myMIME.essence);
// Prints: application/javascript
console.log(String(myMIME));
// Prints: application/javascript;key=valueconst { MIMEType } = require('node:util');
const myMIME = new MIMEType('text/javascript;key=value');
console.log(myMIME.essence);
// Prints: text/javascript
myMIME.type = 'application';
console.log(myMIME.essence);
// Prints: application/javascript
console.log(String(myMIME));
// Prints: application/javascript;key=value
mime.params#
- Type: <MIMEParams>
MIME のパラメータを表す MIMEParams オブジェクトを取得します。このプロパティは読み取り専用です。詳細は MIMEParams のドキュメントを参照してください。
mime.toString()#
- 戻り値: <string>
MIMEType オブジェクトの toString() メソッドは、シリアル化された MIME を返します。
標準への準拠が必要なため、このメソッドはユーザーが MIME のシリアル化プロセスをカスタマイズすることを許可していません。
mime.toJSON()#
- 戻り値: <string>
mime.toString() のエイリアスです。
このメソッドは、MIMEType オブジェクトが JSON.stringify() でシリアル化されるときに自動的に呼び出されます。
import { MIMEType } from 'node:util';
const myMIMES = [
new MIMEType('image/png'),
new MIMEType('image/gif'),
];
console.log(JSON.stringify(myMIMES));
// Prints: ["image/png", "image/gif"]const { MIMEType } = require('node:util');
const myMIMES = [
new MIMEType('image/png'),
new MIMEType('image/gif'),
];
console.log(JSON.stringify(myMIMES));
// Prints: ["image/png", "image/gif"]
クラス: util.MIMEParams#
MIMEParams API は、MIMEType のパラメータへの読み書きアクセスを提供します。
new MIMEParams()#
空のパラメータを持つ新しい MIMEParams オブジェクトを作成します
import { MIMEParams } from 'node:util';
const myParams = new MIMEParams();const { MIMEParams } = require('node:util');
const myParams = new MIMEParams();
mimeParams.entries()#
- 戻り値: <Iterator>
パラメータ内の各名前と値のペアに対するイテレータを返します。イテレータの各項目は JavaScript の Array です。配列の最初の項目は name、2番目の項目は value です。
mimeParams.get(name)#
名前が name である最初の名前と値のペアの値を返します。そのようなペアがない場合は null が返されます。
mimeParams.keys()#
- 戻り値: <Iterator>
各名前と値のペアの名前に対するイテレータを返します。
import { MIMEType } from 'node:util';
const { params } = new MIMEType('text/plain;foo=0;bar=1');
for (const name of params.keys()) {
console.log(name);
}
// Prints:
// foo
// barconst { MIMEType } = require('node:util');
const { params } = new MIMEType('text/plain;foo=0;bar=1');
for (const name of params.keys()) {
console.log(name);
}
// Prints:
// foo
// bar
mimeParams.set(name, value)#
MIMEParams オブジェクト内で name に関連付けられた値を value に設定します。名前が name である既存の名前と値のペアがある場合、最初のそのようなペアの値を value に設定します。
import { MIMEType } from 'node:util';
const { params } = new MIMEType('text/plain;foo=0;bar=1');
params.set('foo', 'def');
params.set('baz', 'xyz');
console.log(params.toString());
// Prints: foo=def;bar=1;baz=xyzconst { MIMEType } = require('node:util');
const { params } = new MIMEType('text/plain;foo=0;bar=1');
params.set('foo', 'def');
params.set('baz', 'xyz');
console.log(params.toString());
// Prints: foo=def;bar=1;baz=xyz
mimeParams[Symbol.iterator]()#
- 戻り値: <Iterator>
mimeParams.entries() のエイリアスです。
import { MIMEType } from 'node:util';
const { params } = new MIMEType('text/plain;foo=bar;xyz=baz');
for (const [name, value] of params) {
console.log(name, value);
}
// Prints:
// foo bar
// xyz bazconst { MIMEType } = require('node:util');
const { params } = new MIMEType('text/plain;foo=bar;xyz=baz');
for (const [name, value] of params) {
console.log(name, value);
}
// Prints:
// foo bar
// xyz baz
util.parseArgs([config])#
-
config<Object> 解析のための引数を提供し、パーサーを設定するために使用されます。configは次のプロパティをサポートしますargs<string[]> 引数文字列の配列。デフォルト:process.argvからexecPathとfilenameを削除したもの。options<Object> パーサーに知られている引数を記述するために使用されます。optionsのキーはオプションの長い名前で、値は次のプロパティを受け入れる <Object> ですtype<string> 引数の型。booleanまたはstringのいずれかでなければなりません。multiple<boolean> このオプションを複数回指定できるかどうか。trueの場合、すべての値が配列に収集されます。falseの場合、オプションの値は最後に指定されたものが優先されます。デフォルト:false。short<string> オプションの単一文字のエイリアス。default<string> | <boolean> | <string[]> | <boolean[]> 解析対象の引数にオプションが表示されない場合に割り当てる値。値はtypeプロパティで指定された型と一致する必要があります。multipleがtrueの場合、それは配列でなければなりません。提供された値が偽値であっても、オプションが解析対象の引数に表示される場合はデフォルト値は適用されません。
strict<boolean> 不明な引数が検出された場合、またはoptionsで設定されたtypeと一致しない引数が渡された場合にエラーをスローするかどうか。デフォルト:true。allowPositionals<boolean> このコマンドが位置引数を受け入れるかどうか。デフォルト:strictがtrueの場合はfalse、それ以外はtrue。allowNegative<boolean>trueの場合、オプション名の前に--no-を付けることで、ブール値オプションを明示的にfalseに設定できます。デフォルト:false。tokens<boolean> 解析されたトークンを返します。これは、追加のチェックを追加したり、トークンを異なる方法で再処理したりするなど、組み込みの動作を拡張するのに役立ちます。デフォルト:false。
-
戻り値: <Object> 解析されたコマンドライン引数
values<Object> 解析されたオプション名とその <string> または <boolean> 値のマッピング。positionals<string[]> 位置引数。tokens<Object[]> | <undefined> parseArgs トークンセクションを参照してください。configにtokens: trueが含まれている場合にのみ返されます。
process.argv を直接操作するよりも高レベルなコマンドライン引数解析APIを提供します。期待される引数の仕様を受け取り、解析されたオプションと位置引数を含む構造化されたオブジェクトを返します。
import { parseArgs } from 'node:util';
const args = ['-f', '--bar', 'b'];
const options = {
foo: {
type: 'boolean',
short: 'f',
},
bar: {
type: 'string',
},
};
const {
values,
positionals,
} = parseArgs({ args, options });
console.log(values, positionals);
// Prints: [Object: null prototype] { foo: true, bar: 'b' } []const { parseArgs } = require('node:util');
const args = ['-f', '--bar', 'b'];
const options = {
foo: {
type: 'boolean',
short: 'f',
},
bar: {
type: 'string',
},
};
const {
values,
positionals,
} = parseArgs({ args, options });
console.log(values, positionals);
// Prints: [Object: null prototype] { foo: true, bar: 'b' } []
parseArgs の tokens#
設定で tokens: true を指定することにより、カスタム動作を追加するための詳細な解析情報が利用可能です。返されるトークンには、以下を記述するプロパティがあります
- すべてのトークン
- オプショントークン
name<string> オプションの長い名前。rawName<string>-fや--fooのように、引数でオプションがどのように使用されたか。value<string> | <undefined> 引数で指定されたオプション値。ブール値オプションの場合は未定義。inlineValue<boolean> | <undefined> オプション値が--foo=barのようにインラインで指定されたかどうか。
- 位置トークン
value<string> 引数内の位置引数の値 (つまりargs[index])。
- オプション終端トークン
返されるトークンは、入力引数で遭遇した順序になっています。引数に複数回現れるオプションは、使用されるたびにトークンを生成します。-xy のような短いオプショングループは、各オプションのトークンに展開されます。したがって、-xxx は3つのトークンを生成します。
例えば、--no-color のような否定オプションのサポートを追加する場合(これは allowNegative がオプションが boolean 型の場合にサポートします)、返されたトークンを再処理して、否定オプションに格納される値を変更することができます。
import { parseArgs } from 'node:util';
const options = {
'color': { type: 'boolean' },
'no-color': { type: 'boolean' },
'logfile': { type: 'string' },
'no-logfile': { type: 'boolean' },
};
const { values, tokens } = parseArgs({ options, tokens: true });
// Reprocess the option tokens and overwrite the returned values.
tokens
.filter((token) => token.kind === 'option')
.forEach((token) => {
if (token.name.startsWith('no-')) {
// Store foo:false for --no-foo
const positiveName = token.name.slice(3);
values[positiveName] = false;
delete values[token.name];
} else {
// Resave value so last one wins if both --foo and --no-foo.
values[token.name] = token.value ?? true;
}
});
const color = values.color;
const logfile = values.logfile ?? 'default.log';
console.log({ logfile, color });const { parseArgs } = require('node:util');
const options = {
'color': { type: 'boolean' },
'no-color': { type: 'boolean' },
'logfile': { type: 'string' },
'no-logfile': { type: 'boolean' },
};
const { values, tokens } = parseArgs({ options, tokens: true });
// Reprocess the option tokens and overwrite the returned values.
tokens
.filter((token) => token.kind === 'option')
.forEach((token) => {
if (token.name.startsWith('no-')) {
// Store foo:false for --no-foo
const positiveName = token.name.slice(3);
values[positiveName] = false;
delete values[token.name];
} else {
// Resave value so last one wins if both --foo and --no-foo.
values[token.name] = token.value ?? true;
}
});
const color = values.color;
const logfile = values.logfile ?? 'default.log';
console.log({ logfile, color });
否定されたオプションを示す使用例、およびオプションが複数の方法で使用された場合に最後に指定されたものが優先される例。
$ node negate.js
{ logfile: 'default.log', color: undefined }
$ node negate.js --no-logfile --no-color
{ logfile: false, color: false }
$ node negate.js --logfile=test.log --color
{ logfile: 'test.log', color: true }
$ node negate.js --no-logfile --logfile=test.log --color --no-color
{ logfile: 'test.log', color: false }
util.parseEnv(content)#
content<string>
.env ファイルの生の内容。
- 戻り値: <Object>
.env ファイルの例を以下に示します
const { parseEnv } = require('node:util');
parseEnv('HELLO=world\nHELLO=oh my\n');
// Returns: { HELLO: 'oh my' }import { parseEnv } from 'node:util';
parseEnv('HELLO=world\nHELLO=oh my\n');
// Returns: { HELLO: 'oh my' }
util.promisify(original)#
original<Function>- 戻り値: <Function>
一般的なエラーファーストのコールバックスタイル、つまり最後の引数として (err, value) => ... コールバックを取る関数を受け取り、プロミスを返すバージョンを返します。
import { promisify } from 'node:util';
import { stat } from 'node:fs';
const promisifiedStat = promisify(stat);
promisifiedStat('.').then((stats) => {
// Do something with `stats`
}).catch((error) => {
// Handle the error.
});const { promisify } = require('node:util');
const { stat } = require('node:fs');
const promisifiedStat = promisify(stat);
promisifiedStat('.').then((stats) => {
// Do something with `stats`
}).catch((error) => {
// Handle the error.
});
または、async function を使用して同等の処理を行います
import { promisify } from 'node:util';
import { stat } from 'node:fs';
const promisifiedStat = promisify(stat);
async function callStat() {
const stats = await promisifiedStat('.');
console.log(`This directory is owned by ${stats.uid}`);
}
callStat();const { promisify } = require('node:util');
const { stat } = require('node:fs');
const promisifiedStat = promisify(stat);
async function callStat() {
const stats = await promisifiedStat('.');
console.log(`This directory is owned by ${stats.uid}`);
}
callStat();
original[util.promisify.custom] プロパティが存在する場合、promisify はその値を返します。カスタムプロミス化関数 を参照してください。
promisify() は、original がすべての場合において最後の引数としてコールバックを取る関数であると想定します。original が関数でない場合、promisify() はエラーをスローします。original が関数であっても、その最後の引数がエラーファーストのコールバックでない場合でも、最後の引数としてエラーファーストのコールバックが渡されます。
クラスメソッドや this を使用する他のメソッドで promisify() を使用すると、特別に処理しない限り期待どおりに動作しない場合があります。
import { promisify } from 'node:util';
class Foo {
constructor() {
this.a = 42;
}
bar(callback) {
callback(null, this.a);
}
}
const foo = new Foo();
const naiveBar = promisify(foo.bar);
// TypeError: Cannot read properties of undefined (reading 'a')
// naiveBar().then(a => console.log(a));
naiveBar.call(foo).then((a) => console.log(a)); // '42'
const bindBar = naiveBar.bind(foo);
bindBar().then((a) => console.log(a)); // '42'const { promisify } = require('node:util');
class Foo {
constructor() {
this.a = 42;
}
bar(callback) {
callback(null, this.a);
}
}
const foo = new Foo();
const naiveBar = promisify(foo.bar);
// TypeError: Cannot read properties of undefined (reading 'a')
// naiveBar().then(a => console.log(a));
naiveBar.call(foo).then((a) => console.log(a)); // '42'
const bindBar = naiveBar.bind(foo);
bindBar().then((a) => console.log(a)); // '42'
カスタムプロミス化関数#
util.promisify.custom シンボルを使用することで、util.promisify() の戻り値を上書きできます
import { promisify } from 'node:util';
function doSomething(foo, callback) {
// ...
}
doSomething[promisify.custom] = (foo) => {
return getPromiseSomehow();
};
const promisified = promisify(doSomething);
console.log(promisified === doSomething[promisify.custom]);
// prints 'true'const { promisify } = require('node:util');
function doSomething(foo, callback) {
// ...
}
doSomething[promisify.custom] = (foo) => {
return getPromiseSomehow();
};
const promisified = promisify(doSomething);
console.log(promisified === doSomething[promisify.custom]);
// prints 'true'
これは、元の関数が最後の引数としてエラーファーストのコールバックを取るという標準的な形式に従わない場合に便利です。
例えば、(foo, onSuccessCallback, onErrorCallback) を受け取る関数の場合
doSomething[util.promisify.custom] = (foo) => {
return new Promise((resolve, reject) => {
doSomething(foo, resolve, reject);
});
};
promisify.custom が定義されているが関数でない場合、promisify() はエラーをスローします。
util.promisify.custom#
- 型: <symbol> 関数のカスタムプロミス化されたバリアントを宣言するために使用できるシンボルです。カスタムプロミス化関数を参照してください。
util.promisify.custom を通じてアクセスできることに加えて、このシンボルはグローバルに登録されており、どの環境でも Symbol.for('nodejs.util.promisify.custom')としてアクセスできます。
例えば、(foo, onSuccessCallback, onErrorCallback) を受け取る関数の場合
const kCustomPromisifiedSymbol = Symbol.for('nodejs.util.promisify.custom');
doSomething[kCustomPromisifiedSymbol] = (foo) => {
return new Promise((resolve, reject) => {
doSomething(foo, resolve, reject);
});
};
util.stripVTControlCharacters(str)#
ANSI エスケープコードが削除された str を返します。
console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m'));
// Prints "value"
util.styleText(format, text[, options])#
format<string> | <Array>util.inspect.colorsで定義されているテキストフォーマットまたはテキストフォーマットの配列。text<string> フォーマットされるテキスト。options<Object>
この関数は、ターミナルでの表示用に渡された format を考慮してフォーマットされたテキストを返します。ターミナルの機能性を認識し、NO_COLOR、NODE_DISABLE_COLORS、FORCE_COLOR 環境変数を通じて設定された構成に従って動作します。
import { styleText } from 'node:util';
import { stderr } from 'node:process';
const successMessage = styleText('green', 'Success!');
console.log(successMessage);
const errorMessage = styleText(
'red',
'Error! Error!',
// Validate if process.stderr has TTY
{ stream: stderr },
);
console.error(errorMessage);const { styleText } = require('node:util');
const { stderr } = require('node:process');
const successMessage = styleText('green', 'Success!');
console.log(successMessage);
const errorMessage = styleText(
'red',
'Error! Error!',
// Validate if process.stderr has TTY
{ stream: stderr },
);
console.error(errorMessage);
util.inspect.colors は italic や underline などのテキストフォーマットも提供しており、両方を組み合わせることができます
console.log(
util.styleText(['underline', 'italic'], 'My italic underlined message'),
);
フォーマットの配列を渡す場合、適用されるフォーマットの順序は左から右であるため、次のスタイルが前のスタイルを上書きする可能性があります。
console.log(
util.styleText(['red', 'green'], 'text'), // green
);
特別なフォーマット値 none は、テキストに追加のスタイリングを適用しません。
フォーマットの完全なリストは修飾子にあります。
クラス: util.TextDecoder#
WHATWG Encoding Standard の TextDecoder API の実装です。
const decoder = new TextDecoder();
const u8arr = new Uint8Array([72, 101, 108, 108, 111]);
console.log(decoder.decode(u8arr)); // Hello
WHATWG がサポートするエンコーディング#
WHATWG Encoding Standard に従い、TextDecoder API がサポートするエンコーディングは以下の表にまとめられています。各エンコーディングには、1つ以上のエイリアスを使用できます。
Node.js のビルド構成によって、サポートされるエンコーディングのセットが異なります。(国際化を参照)
デフォルトでサポートされるエンコーディング (完全なICUデータを使用)#
| エンコーディング | エイリアス |
|---|---|
'ibm866' | '866', 'cp866', 'csibm866' |
'iso-8859-2' | 'csisolatin2', 'iso-ir-101', 'iso8859-2', 'iso88592', 'iso_8859-2', 'iso_8859-2:1987', 'l2', 'latin2' |
'iso-8859-3' | 'csisolatin3', 'iso-ir-109', 'iso8859-3', 'iso88593', 'iso_8859-3', 'iso_8859-3:1988', 'l3', 'latin3' |
'iso-8859-4' | 'csisolatin4', 'iso-ir-110', 'iso8859-4', 'iso88594', 'iso_8859-4', 'iso_8859-4:1988', 'l4', 'latin4' |
'iso-8859-5' | 'csisolatincyrillic', 'cyrillic', 'iso-ir-144', 'iso8859-5', 'iso88595', 'iso_8859-5', 'iso_8859-5:1988' |
'iso-8859-6' | 'arabic', 'asmo-708', 'csiso88596e', 'csiso88596i', 'csisolatinarabic', 'ecma-114', 'iso-8859-6-e', 'iso-8859-6-i', 'iso-ir-127', 'iso8859-6', 'iso88596', 'iso_8859-6', 'iso_8859-6:1987' |
'iso-8859-7' | 'csisolatingreek', 'ecma-118', 'elot_928', 'greek', 'greek8', 'iso-ir-126', 'iso8859-7', 'iso88597', 'iso_8859-7', 'iso_8859-7:1987', 'sun_eu_greek' |
'iso-8859-8' | 'csiso88598e', 'csisolatinhebrew', 'hebrew', 'iso-8859-8-e', 'iso-ir-138', 'iso8859-8', 'iso88598', 'iso_8859-8', 'iso_8859-8:1988', 'visual' |
'iso-8859-8-i' | 'csiso88598i', 'logical' |
'iso-8859-10' | 'csisolatin6', 'iso-ir-157', 'iso8859-10', 'iso885910', 'l6', 'latin6' |
'iso-8859-13' | 'iso8859-13', 'iso885913' |
'iso-8859-14' | 'iso8859-14', 'iso885914' |
'iso-8859-15' | 'csisolatin9', 'iso8859-15', 'iso885915', 'iso_8859-15', 'l9' |
'koi8-r' | 'cskoi8r', 'koi', 'koi8', 'koi8_r' |
'koi8-u' | 'koi8-ru' |
'macintosh' | 'csmacintosh', 'mac', 'x-mac-roman' |
'windows-874' | 'dos-874', 'iso-8859-11', 'iso8859-11', 'iso885911', 'tis-620' |
'windows-1250' | 'cp1250', 'x-cp1250' |
'windows-1251' | 'cp1251', 'x-cp1251' |
'windows-1252' | 'ansi_x3.4-1968', 'ascii', 'cp1252', 'cp819', 'csisolatin1', 'ibm819', 'iso-8859-1', 'iso-ir-100', 'iso8859-1', 'iso88591', 'iso_8859-1', 'iso_8859-1:1987', 'l1', 'latin1', 'us-ascii', 'x-cp1252' |
'windows-1253' | 'cp1253', 'x-cp1253' |
'windows-1254' | 'cp1254', 'csisolatin5', 'iso-8859-9', 'iso-ir-148', 'iso8859-9', 'iso88599', 'iso_8859-9', 'iso_8859-9:1989', 'l5', 'latin5', 'x-cp1254' |
'windows-1255' | 'cp1255', 'x-cp1255' |
'windows-1256' | 'cp1256', 'x-cp1256' |
'windows-1257' | 'cp1257', 'x-cp1257' |
'windows-1258' | 'cp1258', 'x-cp1258' |
'x-mac-cyrillic' | 'x-mac-ukrainian' |
'gbk' | 'chinese', 'csgb2312', 'csiso58gb231280', 'gb2312', 'gb_2312', 'gb_2312-80', 'iso-ir-58', 'x-gbk' |
'gb18030' | |
'big5' | 'big5-hkscs', 'cn-big5', 'csbig5', 'x-x-big5' |
'euc-jp' | 'cseucpkdfmtjapanese', 'x-euc-jp' |
'iso-2022-jp' | 'csiso2022jp' |
'shift_jis' | 'csshiftjis', 'ms932', 'ms_kanji', 'shift-jis', 'sjis', 'windows-31j', 'x-sjis' |
'euc-kr' | 'cseuckr', 'csksc56011987', 'iso-ir-149', 'korean', 'ks_c_5601-1987', 'ks_c_5601-1989', 'ksc5601', 'ksc_5601', 'windows-949' |
Node.js が small-icu オプションでビルドされた場合にサポートされるエンコーディング#
| エンコーディング | エイリアス |
|---|---|
'utf-8' | 'unicode-1-1-utf-8', 'utf8' |
'utf-16le' | 'utf-16' |
'utf-16be' |
ICU が無効な場合にサポートされるエンコーディング#
| エンコーディング | エイリアス |
|---|---|
'utf-8' | 'unicode-1-1-utf-8', 'utf8' |
'utf-16le' | 'utf-16' |
WHATWG エンコーディング標準に記載されている 'iso-8859-16' エンコーディングはサポートされていません。
new TextDecoder([encoding[, options]])#
新しい TextDecoder インスタンスを作成します。encoding は、サポートされているエンコーディングまたはエイリアスのいずれかを指定できます。
TextDecoder クラスは、グローバルオブジェクトでも利用可能です。
textDecoder.decode([input[, options]])#
input<ArrayBuffer> | <DataView> | <TypedArray> エンコードされたデータを含むArrayBuffer、DataView、またはTypedArrayインスタンス。options<Object>stream<boolean>trueの場合、追加のデータチャンクが期待されます。デフォルト:false。
- 戻り値: <string>
input をデコードして文字列を返します。options.stream が true の場合、input の末尾で発生する不完全なバイトシーケンスは内部でバッファリングされ、次の textDecoder.decode() の呼び出し後に発行されます。
textDecoder.fatal が true の場合、発生したデコードエラーは TypeError がスローされる結果となります。
クラス: util.TextEncoder#
WHATWG エンコーディング標準の TextEncoder API の実装です。TextEncoder のすべてのインスタンスは UTF-8 エンコーディングのみをサポートします。
const encoder = new TextEncoder();
const uint8array = encoder.encode('this is some data');
TextEncoder クラスは、グローバルオブジェクトでも利用可能です。
textEncoder.encode([input])#
input<string> エンコードするテキスト。デフォルト: 空文字列。- 戻り値: <Uint8Array>
input 文字列を UTF-8 でエンコードし、エンコードされたバイトを含む Uint8Array を返します。
textEncoder.encodeInto(src, dest)#
src<string> エンコードするテキスト。dest<Uint8Array> エンコード結果を保持する配列。- 戻り値: <Object>
src 文字列を dest Uint8Array に UTF-8 でエンコードし、読み取られた Unicode コードユニットと書き込まれた UTF-8 バイトを含むオブジェクトを返します。
const encoder = new TextEncoder();
const src = 'this is some data';
const dest = new Uint8Array(10);
const { read, written } = encoder.encodeInto(src, dest);
util.toUSVString(string)#
string<string>
サロゲートコードポイント(または同等に、ペアになっていないサロゲートコードユニット)を Unicode の「置換文字」U+FFFD に置き換えた後の string を返します。
util.transferableAbortController()#
<AbortSignal> が転送可能 (transferable) としてマークされ、structuredClone() や postMessage() で使用できる <AbortController> インスタンスを作成して返します。
util.transferableAbortSignal(signal)#
- `signal` <AbortSignal>
- 戻り値: <AbortSignal>
与えられた <AbortSignal> を、structuredClone() と postMessage() で使用できるように転送可能 (transferable) としてマークします。
const signal = transferableAbortSignal(AbortSignal.timeout(100));
const channel = new MessageChannel();
channel.port2.postMessage(signal, [signal]);
util.aborted(signal, resource)#
- `signal` <AbortSignal>
resource<Object> 中断可能な操作に関連付けられ、弱参照で保持される、null 以外の任意のオブジェクト。signalが中断される前にresourceがガベージコレクションされた場合、Promise は保留状態のままとなり、Node.js がその追跡を停止できるようになります。これは、長時間実行される操作やキャンセル不可能な操作でのメモリリークを防ぐのに役立ちます。- 戻り値: <Promise>
提供された signal の abort イベントをリッスンし、signal が中断されたときに解決される Promise を返します。resource が提供された場合、操作に関連するオブジェクトを弱参照します。そのため、signal が中断される前に resource がガベージコレクションされると、返された Promise は保留状態のままになります。これは、長時間実行される操作やキャンセル不可能な操作でのメモリリークを防ぎます。
const { aborted } = require('node:util');
// Obtain an object with an abortable signal, like a custom resource or operation.
const dependent = obtainSomethingAbortable();
// Pass `dependent` as the resource, indicating the promise should only resolve
// if `dependent` is still in memory when the signal is aborted.
aborted(dependent.signal, dependent).then(() => {
// This code runs when `dependent` is aborted.
console.log('Dependent resource was aborted.');
});
// Simulate an event that triggers the abort.
dependent.on('event', () => {
dependent.abort(); // This will cause the `aborted` promise to resolve.
});import { aborted } from 'node:util';
// Obtain an object with an abortable signal, like a custom resource or operation.
const dependent = obtainSomethingAbortable();
// Pass `dependent` as the resource, indicating the promise should only resolve
// if `dependent` is still in memory when the signal is aborted.
aborted(dependent.signal, dependent).then(() => {
// This code runs when `dependent` is aborted.
console.log('Dependent resource was aborted.');
});
// Simulate an event that triggers the abort.
dependent.on('event', () => {
dependent.abort(); // This will cause the `aborted` promise to resolve.
});
util.types#
util.types は、さまざまな種類の組み込みオブジェクトの型チェックを提供します。instanceof や Object.prototype.toString.call(value) とは異なり、これらのチェックは (プロトタイプのように) JavaScript からアクセス可能なオブジェクトのプロパティを検査せず、通常は C++ への呼び出しのオーバーヘッドがあります。
その結果は、一般的に、値が JavaScript でどのようなプロパティや振る舞いを公開するかについて何も保証しません。これらは主に、JavaScript で型チェックを行うことを好むアドオン開発者にとって有用です。
この API は require('node:util').types または require('node:util/types') を介してアクセス可能です。
util.types.isAnyArrayBuffer(value)#
値が組み込みの <ArrayBuffer> または <SharedArrayBuffer> インスタンスである場合に true を返します。
util.types.isArrayBuffer() と util.types.isSharedArrayBuffer() も参照してください。
util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true
util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true
util.types.isArrayBufferView(value)#
値が型付き配列オブジェクトや <DataView> のような <ArrayBuffer> ビューのインスタンスである場合に true を返します。ArrayBuffer.isView() と同等です。
util.types.isArrayBufferView(new Int8Array()); // true
util.types.isArrayBufferView(Buffer.from('hello world')); // true
util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true
util.types.isArrayBufferView(new ArrayBuffer()); // false
util.types.isArgumentsObject(value)#
値が arguments オブジェクトである場合に true を返します。
function foo() {
util.types.isArgumentsObject(arguments); // Returns true
}
util.types.isArrayBuffer(value)#
値が組み込みの <ArrayBuffer> インスタンスである場合に true を返します。これには <SharedArrayBuffer> インスタンスは含まれません。通常は両方をテストすることが望ましいため、その場合は util.types.isAnyArrayBuffer() を参照してください。
util.types.isArrayBuffer(new ArrayBuffer()); // Returns true
util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false
util.types.isAsyncFunction(value)#
値が非同期関数である場合に true を返します。これは JavaScript エンジンが見ているものを報告するだけです。特に、トランスパイルツールが使用された場合、戻り値は元のソースコードと一致しない可能性があります。
util.types.isAsyncFunction(function foo() {}); // Returns false
util.types.isAsyncFunction(async function foo() {}); // Returns true
util.types.isBigInt64Array(value)#
値が BigInt64Array インスタンスである場合に true を返します。
util.types.isBigInt64Array(new BigInt64Array()); // Returns true
util.types.isBigInt64Array(new BigUint64Array()); // Returns false
util.types.isBigIntObject(value)#
値が BigInt オブジェクト (例: Object(BigInt(123)) で作成されたもの) である場合に true を返します。
util.types.isBigIntObject(Object(BigInt(123))); // Returns true
util.types.isBigIntObject(BigInt(123)); // Returns false
util.types.isBigIntObject(123); // Returns false
util.types.isBigUint64Array(value)#
値が BigUint64Array インスタンスである場合に true を返します。
util.types.isBigUint64Array(new BigInt64Array()); // Returns false
util.types.isBigUint64Array(new BigUint64Array()); // Returns true
util.types.isBooleanObject(value)#
値が真偽値オブジェクト (例: new Boolean() で作成されたもの) である場合に true を返します。
util.types.isBooleanObject(false); // Returns false
util.types.isBooleanObject(true); // Returns false
util.types.isBooleanObject(new Boolean(false)); // Returns true
util.types.isBooleanObject(new Boolean(true)); // Returns true
util.types.isBooleanObject(Boolean(false)); // Returns false
util.types.isBooleanObject(Boolean(true)); // Returns false
util.types.isBoxedPrimitive(value)#
値がボックス化されたプリミティブオブジェクト (例: new Boolean()、new String()、Object(Symbol()) で作成されたもの) である場合に true を返します。
例:
util.types.isBoxedPrimitive(false); // Returns false
util.types.isBoxedPrimitive(new Boolean(false)); // Returns true
util.types.isBoxedPrimitive(Symbol('foo')); // Returns false
util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true
util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true
util.types.isCryptoKey(value)#
value が <CryptoKey> の場合に true を、それ以外の場合は false を返します。
util.types.isDataView(value)#
値が組み込みの <DataView> インスタンスである場合に true を返します。
const ab = new ArrayBuffer(20);
util.types.isDataView(new DataView(ab)); // Returns true
util.types.isDataView(new Float64Array()); // Returns false
ArrayBuffer.isView() も参照してください。
util.types.isDate(value)#
値が組み込みの <Date> インスタンスである場合に true を返します。
util.types.isDate(new Date()); // Returns true
util.types.isExternal(value)#
値がネイティブの External 値である場合に true を返します。
ネイティブの External 値は、ネイティブコードからのアクセスのために生の C++ ポインタ (void*) を含み、他のプロパティを持たない特殊なタイプのオブジェクトです。このようなオブジェクトは、Node.js の内部またはネイティブアドオンによって作成されます。JavaScript では、これらは null プロトタイプを持つ凍結されたオブジェクトです。
#include <js_native_api.h>
#include <stdlib.h>
napi_value result;
static napi_value MyNapi(napi_env env, napi_callback_info info) {
int* raw = (int*) malloc(1024);
napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result);
if (status != napi_ok) {
napi_throw_error(env, NULL, "napi_create_external failed");
return NULL;
}
return result;
}
...
DECLARE_NAPI_PROPERTY("myNapi", MyNapi)
...
import native from 'napi_addon.node';
import { types } from 'node:util';
const data = native.myNapi();
types.isExternal(data); // returns true
types.isExternal(0); // returns false
types.isExternal(new String('foo')); // returns falseconst native = require('napi_addon.node');
const { types } = require('node:util');
const data = native.myNapi();
types.isExternal(data); // returns true
types.isExternal(0); // returns false
types.isExternal(new String('foo')); // returns false
napi_create_external の詳細については、napi_create_external() を参照してください。
util.types.isFloat16Array(value)#
値が組み込みの <Float16Array> インスタンスである場合に true を返します。
util.types.isFloat16Array(new ArrayBuffer()); // Returns false
util.types.isFloat16Array(new Float16Array()); // Returns true
util.types.isFloat16Array(new Float32Array()); // Returns false
util.types.isFloat32Array(value)#
値が組み込みの <Float32Array> インスタンスである場合に true を返します。
util.types.isFloat32Array(new ArrayBuffer()); // Returns false
util.types.isFloat32Array(new Float32Array()); // Returns true
util.types.isFloat32Array(new Float64Array()); // Returns false
util.types.isFloat64Array(value)#
値が組み込みの <Float64Array> インスタンスである場合に true を返します。
util.types.isFloat64Array(new ArrayBuffer()); // Returns false
util.types.isFloat64Array(new Uint8Array()); // Returns false
util.types.isFloat64Array(new Float64Array()); // Returns true
util.types.isGeneratorFunction(value)#
値がジェネレータ関数である場合に true を返します。これは JavaScript エンジンが見ているものを報告するだけです。特に、トランスパイルツールが使用された場合、戻り値は元のソースコードと一致しない可能性があります。
util.types.isGeneratorFunction(function foo() {}); // Returns false
util.types.isGeneratorFunction(function* foo() {}); // Returns true
util.types.isGeneratorObject(value)#
値が組み込みのジェネレータ関数から返されるジェネレータオブジェクトである場合に true を返します。これは JavaScript エンジンが見ているものを報告するだけです。特に、トランスパイルツールが使用された場合、戻り値は元のソースコードと一致しない可能性があります。
function* foo() {}
const generator = foo();
util.types.isGeneratorObject(generator); // Returns true
util.types.isInt8Array(value)#
値が組み込みの <Int8Array> インスタンスである場合に true を返します。
util.types.isInt8Array(new ArrayBuffer()); // Returns false
util.types.isInt8Array(new Int8Array()); // Returns true
util.types.isInt8Array(new Float64Array()); // Returns false
util.types.isInt16Array(value)#
値が組み込みの <Int16Array> インスタンスである場合に true を返します。
util.types.isInt16Array(new ArrayBuffer()); // Returns false
util.types.isInt16Array(new Int16Array()); // Returns true
util.types.isInt16Array(new Float64Array()); // Returns false
util.types.isInt32Array(value)#
値が組み込みの <Int32Array> インスタンスである場合に true を返します。
util.types.isInt32Array(new ArrayBuffer()); // Returns false
util.types.isInt32Array(new Int32Array()); // Returns true
util.types.isInt32Array(new Float64Array()); // Returns false
util.types.isKeyObject(value)#
value が <KeyObject> の場合に true を、それ以外の場合は false を返します。
util.types.isMap(value)#
値が組み込みの <Map> インスタンスである場合に true を返します。
util.types.isMap(new Map()); // Returns true
util.types.isMapIterator(value)#
値が組み込みの <Map> インスタンス用に返されるイテレータである場合に true を返します。
const map = new Map();
util.types.isMapIterator(map.keys()); // Returns true
util.types.isMapIterator(map.values()); // Returns true
util.types.isMapIterator(map.entries()); // Returns true
util.types.isMapIterator(map[Symbol.iterator]()); // Returns true
util.types.isModuleNamespaceObject(value)#
値がモジュール名前空間オブジェクトのインスタンスである場合に true を返します。
import * as ns from './a.js';
util.types.isModuleNamespaceObject(ns); // Returns true
util.types.isNativeError(value)#
Error.isError を使用してください。注意: Node.js v24 の時点では、Error.isError() は現在 util.types.isNativeError() よりも低速です。パフォーマンスが重要な場合は、ご自身の環境で両方をベンチマークすることを検討してください。
値が組み込みの Error 型のコンストラクタによって返された場合に true を返します。
console.log(util.types.isNativeError(new Error())); // true
console.log(util.types.isNativeError(new TypeError())); // true
console.log(util.types.isNativeError(new RangeError())); // true
ネイティブエラー型のサブクラスもネイティブエラーです。
class MyError extends Error {}
console.log(util.types.isNativeError(new MyError())); // true
値がネイティブエラークラスの instanceof であることは、その値に対して isNativeError() が true を返すことと等価ではありません。isNativeError() は異なるレルムから来たエラーに対して true を返しますが、instanceof Error はこれらのエラーに対して false を返します。
import { createContext, runInContext } from 'node:vm';
import { types } from 'node:util';
const context = createContext({});
const myError = runInContext('new Error()', context);
console.log(types.isNativeError(myError)); // true
console.log(myError instanceof Error); // falseconst { createContext, runInContext } = require('node:vm');
const { types } = require('node:util');
const context = createContext({});
const myError = runInContext('new Error()', context);
console.log(types.isNativeError(myError)); // true
console.log(myError instanceof Error); // false
逆に、isNativeError() はネイティブエラーのコンストラクタによって返されなかったすべてのオブジェクトに対して false を返します。これには、ネイティブエラーの instanceof である値も含まれます。
const myError = { __proto__: Error.prototype };
console.log(util.types.isNativeError(myError)); // false
console.log(myError instanceof Error); // true
util.types.isNumberObject(value)#
値が数値オブジェクト (例: new Number() で作成されたもの) である場合に true を返します。
util.types.isNumberObject(0); // Returns false
util.types.isNumberObject(new Number(0)); // Returns true
util.types.isPromise(value)#
値が組み込みの <Promise> である場合に true を返します。
util.types.isPromise(Promise.resolve(42)); // Returns true
util.types.isProxy(value)#
値が <Proxy> インスタンスである場合に true を返します。
const target = {};
const proxy = new Proxy(target, {});
util.types.isProxy(target); // Returns false
util.types.isProxy(proxy); // Returns true
util.types.isRegExp(value)#
値が正規表現オブジェクトである場合に true を返します。
util.types.isRegExp(/abc/); // Returns true
util.types.isRegExp(new RegExp('abc')); // Returns true
util.types.isSet(value)#
値が組み込みの <Set> インスタンスである場合に true を返します。
util.types.isSet(new Set()); // Returns true
util.types.isSetIterator(value)#
値が組み込みの <Set> インスタンス用に返されるイテレータである場合に true を返します。
const set = new Set();
util.types.isSetIterator(set.keys()); // Returns true
util.types.isSetIterator(set.values()); // Returns true
util.types.isSetIterator(set.entries()); // Returns true
util.types.isSetIterator(set[Symbol.iterator]()); // Returns true
util.types.isSharedArrayBuffer(value)#
値が組み込みの <SharedArrayBuffer> インスタンスである場合に true を返します。これには <ArrayBuffer> インスタンスは含まれません。通常は両方をテストすることが望ましいため、その場合は util.types.isAnyArrayBuffer() を参照してください。
util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false
util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true
util.types.isStringObject(value)#
値が文字列オブジェクト (例: new String() で作成されたもの) である場合に true を返します。
util.types.isStringObject('foo'); // Returns false
util.types.isStringObject(new String('foo')); // Returns true
util.types.isSymbolObject(value)#
値が Symbol プリミティブに対して Object() を呼び出すことによって作成されたシンボルオブジェクトである場合に true を返します。
const symbol = Symbol('foo');
util.types.isSymbolObject(symbol); // Returns false
util.types.isSymbolObject(Object(symbol)); // Returns true
util.types.isTypedArray(value)#
値が組み込みの <TypedArray> インスタンスである場合に true を返します。
util.types.isTypedArray(new ArrayBuffer()); // Returns false
util.types.isTypedArray(new Uint8Array()); // Returns true
util.types.isTypedArray(new Float64Array()); // Returns true
ArrayBuffer.isView() も参照してください。
util.types.isUint8Array(value)#
値が組み込みの <Uint8Array> インスタンスである場合に true を返します。
util.types.isUint8Array(new ArrayBuffer()); // Returns false
util.types.isUint8Array(new Uint8Array()); // Returns true
util.types.isUint8Array(new Float64Array()); // Returns false
util.types.isUint8ClampedArray(value)#
値が組み込みの <Uint8ClampedArray> インスタンスである場合に true を返します。
util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false
util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true
util.types.isUint8ClampedArray(new Float64Array()); // Returns false
util.types.isUint16Array(value)#
値が組み込みの <Uint16Array> インスタンスである場合に true を返します。
util.types.isUint16Array(new ArrayBuffer()); // Returns false
util.types.isUint16Array(new Uint16Array()); // Returns true
util.types.isUint16Array(new Float64Array()); // Returns false
util.types.isUint32Array(value)#
値が組み込みの <Uint32Array> インスタンスである場合に true を返します。
util.types.isUint32Array(new ArrayBuffer()); // Returns false
util.types.isUint32Array(new Uint32Array()); // Returns true
util.types.isUint32Array(new Float64Array()); // Returns false
非推奨の API#
以下の API は非推奨であり、もはや使用すべきではありません。既存のアプリケーションやモジュールは、代替アプローチを見つけるために更新されるべきです。
util._extend(target, source)#
Object.assign() を使用してください。util._extend() メソッドは、Node.js の内部モジュール以外で使用されることを意図したものではありませんでした。コミュニティはそれを見つけてとにかく使用しました。
これは非推奨であり、新しいコードでは使用すべきではありません。JavaScript には Object.assign() を通じて非常によく似た組み込み機能が備わっています。
util.isArray(object)#
Array.isArray() を使用してください。Array.isArray() のエイリアスです。
与えられた object が Array の場合は true を返します。それ以外の場合は false を返します。
const util = require('node:util');
util.isArray([]);
// Returns: true
util.isArray(new Array());
// Returns: true
util.isArray({});
// Returns: false