Node.js v21.7.2 ドキュメント
- Node.js v21.7.2
-
► 目次
- Util
util.callbackify(original)
util.debuglog(section[, callback])
util.debug(section)
util.deprecate(fn, msg[, code])
util.format(format[, ...args])
util.formatWithOptions(inspectOptions, format[, ...args])
util.getSystemErrorName(err)
util.getSystemErrorMap()
util.inherits(constructor, superConstructor)
util.inspect(object[, options])
util.inspect(object[, showHidden[, depth[, colors]]])
util.isDeepStrictEqual(val1, val2)
- クラス:
util.MIMEType
- クラス:
util.MIMEParams
util.parseArgs([config])
util.parseEnv(content)
util.promisify(original)
util.stripVTControlCharacters(str)
util.styleText(format, text)
- クラス:
util.TextDecoder
- クラス:
util.TextEncoder
util.toUSVString(string)
util.transferableAbortController()
util.transferableAbortSignal(signal)
util.aborted(signal, resource)
util.types
util.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.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.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._extend(target, source)
util.isArray(object)
util.isBoolean(object)
util.isBuffer(object)
util.isDate(object)
util.isError(object)
util.isFunction(object)
util.isNull(object)
util.isNullOrUndefined(object)
util.isNumber(object)
util.isObject(object)
util.isPrimitive(object)
util.isRegExp(object)
util.isString(object)
util.isSymbol(object)
util.isUndefined(object)
util.log(string)
- Util
-
► インデックス
- アサーションテスト
- 非同期コンテキスト追跡
- Async hooks
- Buffer
- C++ アドオン
- Node-API を使用した C/C++ アドオン
- C++ エンベッダー API
- 子プロセス
- Cluster
- コマンドラインオプション
- Console
- Corepack
- Crypto
- デバッガー
- 非推奨 API
- 診断チャネル
- DNS
- Domain
- エラー
- Events
- ファイルシステム
- グローバル
- HTTP
- HTTP/2
- HTTPS
- インスペクター
- 国際化
- モジュール: CommonJS モジュール
- モジュール: ECMAScript モジュール
- モジュール:
node:module
API - モジュール: パッケージ
- Net
- OS
- Path
- パフォーマンスフック
- 権限
- Process
- Punycode
- クエリ文字列
- Readline
- REPL
- Report
- 単一実行可能アプリケーション
- Stream
- 文字列デコーダー
- テストランナー
- タイマー
- TLS/SSL
- トレースイベント
- TTY
- UDP/データグラム
- URL
- ユーティリティ
- V8
- VM
- WASI
- Web Crypto API
- Web Streams API
- Worker threads
- Zlib
- ► その他のバージョン
- ► オプション
Util#
ソースコード: lib/util.js
node:util
モジュールは、Node.js の内部 API のニーズをサポートします。多くのユーティリティは、アプリケーションおよびモジュールの開発者にとっても役立ちます。アクセスするには
const util = require('node:util');
util.callbackify(original)
#
original
<Function>async
関数- 返り値: <Function> コールバック形式の関数
async
関数 (または Promise
を返す関数) を受け取り、エラーファーストのコールバック形式に従う関数、つまり最後の引数として (err, value) => ...
コールバックを受け取る関数を返します。コールバックでは、最初の引数がリジェクト理由 (または Promise
が解決した場合は null
) になり、2 番目の引数が解決された値になります。
const util = require('node:util');
async function fn() {
return 'hello world';
}
const callbackFunction = util.callbackify(fn);
callbackFunction((err, ret) => {
if (err) throw err;
console.log(ret);
});
出力:
hello world
コールバックは非同期的に実行され、スタックトレースは制限されます。コールバックがスローされた場合、プロセスは 'uncaughtException'
イベントを発行し、処理されない場合は終了します。
null
はコールバックの最初の引数として特別な意味を持つため、ラップされた関数が falsy な値を理由として Promise
をリジェクトした場合、その値は、元の値を reason
という名前のフィールドに格納した Error
でラップされます。
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()
と同様に動作します。そうでない場合、返される関数は no-op です。
const util = require('node:util');
const debuglog = util.debuglog('foo');
debuglog('hello from foo [%d]', 123);
このプログラムが環境内で NODE_DEBUG=foo
を設定して実行される場合、次のような出力が生成されます。
FOO 3245: hello from foo [123]
ここで、3245
はプロセス ID です。その環境変数を設定せずに実行した場合、何も出力されません。
section
はワイルドカードもサポートします。
const util = require('node:util');
const debuglog = util.debuglog('foo-bar');
debuglog('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
引数を使用すると、ロギング関数を、初期化や不要なラッピングがない別の関数に置き換えることができます。
const util = require('node:util');
let debuglog = util.debuglog('internals', (debug) => {
// Replace with a logging function that optimizes out
// testing if the section is enabled
debuglog = debug;
});
debuglog().enabled
#
util.debuglog().enabled
ゲッターは、NODE_DEBUG
環境変数の存在に基づいて条件で使用できるテストを作成するために使用されます。section
名がその環境変数の値内に表示される場合、返される値は true
になります。そうでない場合、返される値は false
になります。
const util = require('node:util');
const enabled = util.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
(関数またはクラス)を非推奨としてマークされるようにラップします。
const util = require('node:util');
exports.obsoleteFunction = util.deprecate(() => {
// Do something here.
}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');
呼び出されると、util.deprecate()
は、'warning'
イベントを使用して DeprecationWarning
を発行する関数を返します。警告は、返された関数が最初に呼び出されたときに発行され、stderr
に出力されます。警告が発行された後、ラップされた関数は警告を発することなく呼び出されます。
同じオプションの code
が util.deprecate()
の複数の呼び出しで提供された場合、その code
に対して警告は一度だけ発行されます。
const util = require('node:util');
const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001');
const fn2 = util.deprecate(someOtherFunction, someOtherMessage, '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.format(format[, ...args])
#
format
<string>printf
のようなフォーマット文字列。
util.format()
メソッドは、最初の引数を printf
のようなフォーマット文字列として使用してフォーマットされた文字列を返します。これには、0個以上のフォーマット指定子を含めることができます。各指定子は、対応する引数から変換された値に置き換えられます。サポートされている指定子は次のとおりです。
%s
:String
は、BigInt
、Object
、および-0
を除くすべての値を変換するために使用されます。BigInt
の値はn
で表され、ユーザー定義のtoString
関数を持たないオブジェクトは、{ depth: 0, colors: false, compact: 3 }
オプションを指定してutil.inspect()
を使用して検査されます。%d
:Number
は、BigInt
とSymbol
を除くすべての値を変換するために使用されます。%i
:parseInt(value, 10)
は、BigInt
とSymbol
を除くすべての値に使用されます。%f
:parseFloat(value)
は、Symbol
を除くすべての値に使用されます。%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'
1つの引数のみが util.format()
に渡された場合、フォーマットなしでそのまま返されます。
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.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.inherits(constructor, superConstructor)
#
extends
キーワードを使用してください。constructor
<Function>superConstructor
<Function>
util.inherits()
の使用は推奨されません。ES6 の class
および extends
キーワードを使用して、言語レベルの継承サポートを取得してください。また、2 つのスタイルは意味的に互換性がないことにも注意してください。
1つの コンストラクタ から別のコンストラクタにプロトタイプメソッドを継承します。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 の例
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
,Set
,WeakMap
, およびWeakSet
要素の最大数を指定します。すべての要素を表示するには、null
またはInfinity
に設定します。要素を表示しない場合は、0
または負の数に設定します。デフォルト:100
。maxStringLength
<integer> フォーマット時に含める最大文字数を指定します。すべての要素を表示するには、null
またはInfinity
に設定します。文字を表示しない場合は、0
または負の数に設定します。デフォルト:10000
。breakLength
<integer> 入力値を複数行に分割する長さを指定します。(compact
がtrue
に設定されている場合、または任意の数値が1
以上の場合と組み合わせて)入力を単一行としてフォーマットするには、Infinity
に設定します。デフォルト:80
。compact
<boolean> | <integer> これをfalse
に設定すると、各オブジェクトキーが新しい行に表示されます。breakLength
よりも長いテキストでは改行されます。数値に設定すると、すべてのプロパティがbreakLength
に収まる限り、最も内側のn
個の要素が1行にまとめられます。短い配列要素もグループ化されます。詳細については、以下の例を参照してください。デフォルト: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()
は、コンストラクターの名前や@@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] {}'
循環参照は、参照インデックスを使用してアンカーを指します。
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
オブジェクトのすべてのプロパティを検査します。
const util = require('node:util');
console.log(util.inspect(util, { showHidden: true, depth: null }));
次の例は、compact
オプションの効果を強調表示します。
const util = 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(util.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(util.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回取得すると、異なる出力になる可能性があります。さらに、強い参照が残っていないエントリは、いつでもガベージコレクションされる可能性があります。
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()
の結果に影響を与えないようになります。
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桁ごとにアンダースコアを追加します。
const { inspect } = require('node:util');
const thousand = 1_000;
const million = 1_000_000;
const bigNumber = 123_456_789n;
const bigDecimal = 1_234.123_45;
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()
は、デバッグを目的とした同期メソッドです。最大出力長は約128MiBです。出力が長くなる入力は切り捨てられます。
util.inspect
の色をカスタマイズする#
util.inspect
の色出力(有効な場合)は、util.inspect.styles
およびutil.inspect.colors
プロパティを介してグローバルにカスタマイズできます。
util.inspect.styles
は、スタイル名をutil.inspect.colors
の色に関連付けるマップです。
デフォルトのスタイルと関連付けられた色は次のとおりです。
bigint
:yellow
boolean
:yellow
date
:magenta
module
:underline
name
: (スタイルなし)null
:bold
number
:yellow
regexp
:red
special
:cyan
(例:Proxies
)string
:green
symbol
:green
undefined
:grey
カラースタイルは、すべての端末でサポートされていない可能性のあるANSI制御コードを使用します。カラーサポートを確認するには、tty.hasColors()
を使用してください。
定義済みの制御コードを以下に示します(「修飾子」、「前景色」、および「背景色」としてグループ化されています)。
修飾子#
修飾子のサポートは端末によって異なります。サポートされていない場合は、ほとんどの場合無視されます。
reset
- すべての(カラー)修飾子をデフォルトにリセットします- bold - テキストを太字にします
- italic - テキストを斜体にします
- underline - テキストに下線を引きます
strikethrough- テキストの中央に水平線を引きます(エイリアス:strikeThrough
,crossedout
,crossedOut
)hidden
- テキストを出力しますが、見えなくします(エイリアス: conceal)- dim - 彩度を下げます(エイリアス:
faint
) - overlined - テキストに上線を引きます
- blink - テキストを一定の間隔で非表示にしたり表示したりします
- inverse - 前景色と背景色を入れ替えます(エイリアス:
swapcolors
,swapColors
) - doubleunderline - テキストに二重下線を引きます(エイリアス:
doubleUnderline
) - framed - テキストの周りにフレームを描画します
前景色#
black
red
green
yellow
blue
magenta
cyan
white
gray
(エイリアス:grey
,blackBright
)redBright
greenBright
yellowBright
blueBright
magentaBright
cyanBright
whiteBright
背景色#
bgBlack
bgRed
bgGreen
bgYellow
bgBlue
bgMagenta
bgCyan
bgWhite
bgGray
(エイリアス:bgGrey
,bgBlackBright
)bgRedBright
bgGreenBright
bgYellowBright
bgBlueBright
bgMagentaBright
bgCyanBright
bgWhiteBright
オブジェクトのカスタム検査関数#
オブジェクトは、独自の[util.inspect.custom](depth, opts, inspect)
関数を定義することもできます。この関数をutil.inspect()
が呼び出し、オブジェクトを検査する際にその結果を使用します。
const util = require('node:util');
class Box {
constructor(value) {
this.value = value;
}
[util.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);
util.inspect(box);
// Returns: "Box< true >"
カスタム[util.inspect.custom](depth, opts, inspect)
関数は通常、文字列を返しますが、util.inspect()
によって適切にフォーマットされる任意の型の値を返すこともできます。
const util = require('node:util');
const obj = { foo: 'this will not show up in the inspect() output' };
obj[util.inspect.custom] = (depth) => {
return { bar: 'baz' };
};
util.inspect(obj);
// Returns: "{ bar: 'baz' }"
util.inspect.custom
#
- <symbol> カスタム検査関数を宣言するために使用できるものです。
このシンボルは、util.inspect.custom
を介してアクセスできるだけでなく、グローバルに登録されており、任意の環境で Symbol.for('nodejs.util.inspect.custom')
としてアクセスできます。
これを使用することで、カスタムの inspect 関数が Node.js 環境で使用され、ブラウザでは無視されるように、移植可能な方法でコードを記述できます。util.inspect()
関数自体は、さらなる移植性を可能にするために、カスタムの 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()
オプションを含むオブジェクトに設定する必要があります。オプションのプロパティを直接設定することもサポートされています。
const util = require('node:util');
const arr = Array(101).fill(0);
console.log(arr); // Logs the truncated array
util.inspect.defaultOptions.maxArrayLength = null;
console.log(arr); // logs the full array
util.isDeepStrictEqual(val1, val2)
#
val1
と val2
の間に深い厳密な等価性がある場合は true
を返します。それ以外の場合は false
を返します。
深い厳密な等価性に関する詳細については、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/plain
const { MIMEType } = require('node:util');
const myMIME = new MIMEType({ toString: () => 'text/plain' });
console.log(String(myMIME));
// Prints: text/plain
mime.type
#
MIME の type 部分を取得および設定します。
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/javascript
const { 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
#
MIME の subtype 部分を取得および設定します。
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/javascript
const { 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
#
MIME の essence を取得します。このプロパティは読み取り専用です。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=value
const { 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
#
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.delete(name)
#
name
<string>
名前が name
であるすべての名前と値のペアを削除します。
mimeParams.entries()
#
- 戻り値: <Iterator>
パラメータ内の各名前と値のペアを反復処理するイテレータを返します。イテレータの各項目は JavaScript の Array
です。配列の最初の項目は name
で、配列の2番目の項目は value
です。
mimeParams.get(name)
#
名前が name
である最初の名前と値のペアの値を返します。そのようなペアがない場合は、null
が返されます。
mimeParams.has(name)
#
名前が name
である名前と値のペアが少なくとも1つ存在する場合は true
を返します。
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
// bar
const { 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=xyz
const { 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.values()
#
- 戻り値: <Iterator>
各名前と値のペアの値を反復処理するイテレータを返します。
mimeParams[@@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 baz
const { 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[]> 引数文字列の配列。デフォルト:execPath
とfilename
が削除されたprocess.argv
。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
。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
のように、argsでオプションがどのように使用されたか。value
<string> | <undefined> argsで指定されたオプション値。booleanオプションの場合は undefined。inlineValue
<boolean> | <undefined>--foo=bar
のように、オプション値がインラインで指定されたかどうか。
- 位置引数トークン
value
<string> args内の位置引数の値(つまりargs[index]
)。
- オプション終端トークン
返されたトークンは、入力argsで検出された順序になります。argsに複数回表示されるオプションは、使用ごとにトークンを生成します。-xy
のような短いオプショングループは、各オプションのトークンに展開されます。したがって、-xxx
は3つのトークンを生成します。
たとえば、--no-color
のような否定オプションのサポートを追加するために、返されたトークンを再処理して、否定オプションに格納された値を変更できます。
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) => ...
コールバックを取る関数)を受け取り、Promiseを返すバージョンを返します。
const util = require('node:util');
const fs = require('node:fs');
const stat = util.promisify(fs.stat);
stat('.').then((stats) => {
// Do something with `stats`
}).catch((error) => {
// Handle the error.
});
または、同等の方法で async function
を使用します。
const util = require('node:util');
const fs = require('node:fs');
const stat = util.promisify(fs.stat);
async function callStat() {
const stats = await stat('.');
console.log(`This directory is owned by ${stats.uid}`);
}
callStat();
original[util.promisify.custom]
プロパティが存在する場合、promisify
はその値を返します。 カスタムプロミス化関数を参照してください。
promisify()
は、original
が常に最後の引数としてコールバックを取る関数であると想定します。original
が関数でない場合、promisify()
はエラーをスローします。original
が関数であるが、最後の引数がエラーファーストのコールバックでない場合でも、エラーファーストのコールバックが最後の引数として渡されます。
this
を使用するクラスメソッドまたはその他のメソッドで promisify()
を使用すると、特別に処理しない限り、期待どおりに動作しない場合があります。
const util = require('node:util');
class Foo {
constructor() {
this.a = 42;
}
bar(callback) {
callback(null, this.a);
}
}
const foo = new Foo();
const naiveBar = util.promisify(foo.bar);
// TypeError: Cannot read property 'a' of undefined
// 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()
の戻り値をオーバーライドできます。
const util = require('node:util');
function doSomething(foo, callback) {
// ...
}
doSomething[util.promisify.custom] = (foo) => {
return getPromiseSomehow();
};
const promisified = util.promisify(doSomething);
console.log(promisified === doSomething[util.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)
#
この関数は、渡された format
を考慮して、フォーマットされたテキストを返します。
import { styleText } from 'node:util';
const errorMessage = styleText('red', 'Error! Error!');
console.log(errorMessage);
const { styleText } = require('node:util');
const errorMessage = styleText('red', 'Error! Error!');
console.log(errorMessage);
util.inspect.colors
は、italic
や underline
などのテキスト形式も提供しており、両方を組み合わせることができます。
console.log(
util.styleText('underline', util.styleText('italic', 'My italic underlined message')),
);
フォーマットの完全なリストは、修飾子にあります。
クラス: 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 Encoding Standardにリストされている'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
がスローされます。
textDecoder.encoding
#
TextDecoder
インスタンスでサポートされているエンコーディング。
textDecoder.fatal
#
デコードエラーの結果TypeError
がスローされる場合は、値はtrue
になります。
textDecoder.ignoreBOM
#
デコード結果にバイトオーダーマークが含まれる場合、値はtrue
になります。
クラス: util.TextEncoder
#
WHATWG Encoding Standard 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);
textEncoder.encoding
#
TextEncoder
インスタンスでサポートされているエンコーディング。常に'utf-8'
に設定されます。
util.toUSVString(string)
#
string
<string>
サロゲートコードポイント(または同等の、ペアになっていないサロゲートコードユニット)をUnicodeの「置換文字」U+FFFDに置き換えた後のstring
を返します。
util.transferableAbortController()
#
<AbortController>インスタンスを作成して返し、その<AbortSignal>は転送可能としてマークされ、structuredClone()
またはpostMessage()
で使用できます。
util.transferableAbortSignal(signal)
#
signal
<AbortSignal>- 戻り値: <AbortSignal>
指定された<AbortSignal>を転送可能としてマークし、structuredClone()
およびpostMessage()
で使用できるようにします。
const signal = transferableAbortSignal(AbortSignal.timeout(100));
const channel = new MessageChannel();
channel.port2.postMessage(signal, [signal]);
util.aborted(signal, resource)
#
signal
<AbortSignal>resource
<Object> 弱く保持される参照を持つ、null以外のエンティティ。- 戻り値: <Promise>
提供されたsignal
でabortイベントをリッスンし、signal
が中止されたときに履行されるPromiseを返します。渡されたresource
がsignal
が中止される前にガベージコレクションされた場合、返されたPromiseは無期限に保留されたままになります。
const { aborted } = require('node:util');
const dependent = obtainSomethingAbortable();
aborted(dependent.signal, dependent).then(() => {
// Do something when dependent is aborted.
});
dependent.on('event', () => {
dependent.abort();
});
import { aborted } from 'node:util';
const dependent = obtainSomethingAbortable();
aborted(dependent.signal, dependent).then(() => {
// Do something when dependent is aborted.
});
dependent.on('event', () => {
dependent.abort();
});
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)
#
値がasync functionである場合に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.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
のfrozenオブジェクトです。
#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)
...
const native = require('napi_addon.node');
const data = native.myNapi();
util.types.isExternal(data); // returns true
util.types.isExternal(0); // returns false
util.types.isExternal(new String('foo')); // returns false
napi_create_external
の詳細については、napi_create_external()
を参照してください。
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
型のコンストラクターによって返された場合に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
を返します。
const vm = require('node:vm');
const context = vm.createContext({});
const myError = vm.runInContext('new Error()', context);
console.log(util.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
util.types.isWeakMap(value)
#
値が組み込みのWeakMap
インスタンスである場合はtrue
を返します。
util.types.isWeakMap(new WeakMap()); // Returns true
util.types.isWeakSet(value)
#
値が組み込みのWeakSet
インスタンスである場合はtrue
を返します。
util.types.isWeakSet(new WeakSet()); // Returns true
非推奨の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
util.isBoolean(object)
#
typeof value === 'boolean'
を使用してください。与えられたobject
がBoolean
である場合はtrue
を返します。それ以外の場合はfalse
を返します。
const util = require('node:util');
util.isBoolean(1);
// Returns: false
util.isBoolean(0);
// Returns: false
util.isBoolean(false);
// Returns: true
util.isBuffer(object)
#
Buffer.isBuffer()
を使用してください。与えられたobject
がBuffer
である場合はtrue
を返します。それ以外の場合はfalse
を返します。
const util = require('node:util');
util.isBuffer({ length: 0 });
// Returns: false
util.isBuffer([]);
// Returns: false
util.isBuffer(Buffer.from('hello world'));
// Returns: true
util.isDate(object)
#
util.types.isDate()
を使用してください。与えられたobject
がDate
である場合はtrue
を返します。それ以外の場合はfalse
を返します。
const util = require('node:util');
util.isDate(new Date());
// Returns: true
util.isDate(Date());
// false (without 'new' returns a String)
util.isDate({});
// Returns: false
util.isError(object)
#
util.types.isNativeError()
を使用してください。与えられたobject
がError
である場合はtrue
を返します。それ以外の場合はfalse
を返します。
const util = require('node:util');
util.isError(new Error());
// Returns: true
util.isError(new TypeError());
// Returns: true
util.isError({ name: 'Error', message: 'an error occurred' });
// Returns: false
このメソッドはObject.prototype.toString()
の動作に依存しています。object
引数が@@toStringTag
を操作すると、誤った結果が得られる可能性があります。
const util = require('node:util');
const obj = { name: 'Error', message: 'an error occurred' };
util.isError(obj);
// Returns: false
obj[Symbol.toStringTag] = 'Error';
util.isError(obj);
// Returns: true
util.isFunction(object)
#
typeof value === 'function'
を使用してください。与えられたobject
がFunction
である場合はtrue
を返します。それ以外の場合はfalse
を返します。
const util = require('node:util');
function Foo() {}
const Bar = () => {};
util.isFunction({});
// Returns: false
util.isFunction(Foo);
// Returns: true
util.isFunction(Bar);
// Returns: true
util.isNull(object)
#
value === null
を使用してください。与えられたobject
が厳密にnull
である場合はtrue
を返します。それ以外の場合はfalse
を返します。
const util = require('node:util');
util.isNull(0);
// Returns: false
util.isNull(undefined);
// Returns: false
util.isNull(null);
// Returns: true
util.isNullOrUndefined(object)
#
value === undefined || value === null
を使用してください。与えられたobject
がnull
またはundefined
である場合はtrue
を返します。それ以外の場合はfalse
を返します。
const util = require('node:util');
util.isNullOrUndefined(0);
// Returns: false
util.isNullOrUndefined(undefined);
// Returns: true
util.isNullOrUndefined(null);
// Returns: true
util.isNumber(object)
#
typeof value === 'number'
を使用してください。与えられたobject
がNumber
である場合はtrue
を返します。それ以外の場合はfalse
を返します。
const util = require('node:util');
util.isNumber(false);
// Returns: false
util.isNumber(Infinity);
// Returns: true
util.isNumber(0);
// Returns: true
util.isNumber(NaN);
// Returns: true
util.isObject(object)
#
value !== null && typeof value === 'object'
を使用してください。与えられたobject
が厳密にObject
であり、かつFunction
ではない場合(JavaScriptでは関数もオブジェクトですが)はtrue
を返します。それ以外の場合はfalse
を返します。
const util = require('node:util');
util.isObject(5);
// Returns: false
util.isObject(null);
// Returns: false
util.isObject({});
// Returns: true
util.isObject(() => {});
// Returns: false
util.isPrimitive(object)
#
(typeof value !== 'object' && typeof value !== 'function') || value === null
を使用してください。与えられたobject
がプリミティブ型である場合はtrue
を返します。それ以外の場合はfalse
を返します。
const util = require('node:util');
util.isPrimitive(5);
// Returns: true
util.isPrimitive('foo');
// Returns: true
util.isPrimitive(false);
// Returns: true
util.isPrimitive(null);
// Returns: true
util.isPrimitive(undefined);
// Returns: true
util.isPrimitive({});
// Returns: false
util.isPrimitive(() => {});
// Returns: false
util.isPrimitive(/^$/);
// Returns: false
util.isPrimitive(new Date());
// Returns: false
util.isRegExp(object)
#
与えられたobject
がRegExp
である場合はtrue
を返します。それ以外の場合はfalse
を返します。
const util = require('node:util');
util.isRegExp(/some regexp/);
// Returns: true
util.isRegExp(new RegExp('another regexp'));
// Returns: true
util.isRegExp({});
// Returns: false
util.isString(object)
#
typeof value === 'string'
を使用してください。与えられたobject
がstring
である場合はtrue
を返します。それ以外の場合はfalse
を返します。
const util = require('node:util');
util.isString('');
// Returns: true
util.isString('foo');
// Returns: true
util.isString(String('foo'));
// Returns: true
util.isString(5);
// Returns: false
util.isSymbol(object)
#
typeof value === 'symbol'
を使用してください。与えられたobject
がSymbol
である場合はtrue
を返します。それ以外の場合はfalse
を返します。
const util = require('node:util');
util.isSymbol(5);
// Returns: false
util.isSymbol('foo');
// Returns: false
util.isSymbol(Symbol('foo'));
// Returns: true
util.isUndefined(object)
#
value === undefined
を使用してください。与えられたobject
がundefined
である場合はtrue
を返します。それ以外の場合はfalse
を返します。
const util = require('node:util');
const foo = undefined;
util.isUndefined(5);
// Returns: false
util.isUndefined(foo);
// Returns: true
util.isUndefined(null);
// Returns: false
util.log(string)
#
string
<string>
util.log()
メソッドは、指定されたstring
を、タイムスタンプを含めてstdout
に出力します。
const util = require('node:util');
util.log('Timestamped message.');