util module
node:util
モジュールは、内部 API のニーズ Node.js サポートしています。 ユーティリティの多くは、アプリケーションやモジュールの開発者にも役立ちます。 アクセスするには:
import util from 'node:util';
ソース
クラス
MIMEParams |
|
MIMEType |
MIMEType クラス ブラウザー規則に従って、 MIME 文字列は、複数の意味のあるコンポーネントを含む構造化文字列です。 解析すると、これらの各コンポーネントのプロパティを含む |
TextDecoder |
WHATWG Encoding Standard
|
TextEncoder |
WHATWG Encoding Standard
|
インターフェイス
CallSiteObject | |
CustomPromisifyLegacy | |
CustomPromisifySymbol | |
DebugLogger | |
EncodeIntoResult | |
InspectOptions | |
InspectOptionsStylized | |
ParseArgsConfig | |
ParseArgsOptionDescriptor | |
ParseArgsOptionsConfig |
型エイリアス
CustomInspectFunction | |
CustomPromisify | |
DebugLoggerFunction | |
DiffEntry | |
ParseArgsOptionsType |
parseArgs で使用される引数の型。 |
Style |
関数
aborted(Abort |
指定された
|
add |
指定された URL にパラメーターを追加します |
assign(any[]) | 列挙可能なすべてのプロパティの値を 1 つ以上のソース オブジェクトからターゲット オブジェクトにコピーし、ターゲット オブジェクトを返します。 |
auto |
埋め込み URL に autoAuth=true が含まれているかどうかを確認します。 |
callbackify(() => Promise<void>) |
次の内容が出力されます。
コールバックは非同期的に実行され、スタック トレースが制限されます。
コールバックがスローされると、プロセスは
|
callbackify<T1, T2, T3, T4, T5, T6, TResult>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<TResult>) | |
callbackify<T1, T2, T3, T4, T5, T6>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<void>) | |
callbackify<T1, T2, T3, T4, T5, TResult>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>) | |
callbackify<T1, T2, T3, T4, T5>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>) | |
callbackify<T1, T2, T3, T4, TResult>((arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>) | |
callbackify<T1, T2, T3, T4>((arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>) | |
callbackify<T1, T2, T3, TResult>((arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>) | |
callbackify<T1, T2, T3>((arg1: T1, arg2: T2, arg3: T3) => Promise<void>) | |
callbackify<T1, T2, TResult>((arg1: T1, arg2: T2) => Promise<TResult>) | |
callbackify<T1, T2>((arg1: T1, arg2: T2) => Promise<void>) | |
callbackify<T1, TResult>((arg1: T1) => Promise<TResult>) | |
callbackify<T1>((arg1: T1) => Promise<void>) | |
callbackify<TResult>(() => Promise<TResult>) | |
create |
ランダムな 5 ~ 6 文字の文字列を生成します。 |
debuglog(string, (fn: Debug |
このプログラムを環境内の
ここで、
環境内で
省略可能な
|
deprecate<T>(T, string, string) |
呼び出されると、
|
diff(string | (readonly string[]), string | (readonly string[])) |
値が等しい場合は、空の配列が返されます。
|
find<T>((x: T) => boolean, T[]) | 指定した述語と一致する配列内の最初の値を検索します。 |
find |
指定した述語と一致する配列内の最初の値のインデックスを検索します。 |
format(any, any[]) |
指定子に対応する引数がない場合は、置き換えされません。
書式指定文字列の一部ではない値は、型が 指定子の数よりも多くの引数が
最初の引数に有効な書式指定子が含まれていない場合、
|
format |
この関数は、
|
generateUUID() | 20 文字の uuid を生成します。 |
get |
|
get |
呼び出し元関数のスタックを含む呼び出しサイト オブジェクトの配列を返します。
オプション
|
get |
乱数を返します。 |
get |
Node.js API から使用可能なすべてのシステム エラー コードのマップを返します。
エラー コードとエラー名の間のマッピングはプラットフォームに依存します。
一般的なエラーの名前については、
|
get |
Node.js API から取得された数値エラー コードの文字列メッセージを返します。 エラー コードと文字列メッセージの間のマッピングは、プラットフォームに依存します。
|
get |
Node.js API から取得された数値エラー コードの文字列名を返します。
エラー コードとエラー名の間のマッピングはプラットフォームに依存します。
一般的なエラーの名前については、
|
get |
2 つの日付間の時間間隔をミリ秒単位で返します。 |
inherits(unknown, unknown) |
ある コンストラクター から別のコンストラクターにプロトタイプ メソッドを継承します。
これにより、主に
|
inspect(any, boolean, null | number, boolean) |
循環参照は、参照インデックスを使用してアンカーを指します。
次の例では、
次の例では、
|
inspect(any, Inspect |
|
is |
指定した
|
is |
指定した
|
is |
指定した
|
is |
埋め込み型が作成用であるかどうかを確認します |
is |
指定した
|
is |
詳細な厳密な等価性の詳細については、 |
is |
指定した
このメソッドは、
|
is |
指定した
|
is |
指定された
|
is |
指定した
|
is |
指定した
|
is |
指定した
|
is |
指定した
|
is |
埋め込み URL が RDL レポート用であるかどうかを確認します。 |
is |
指定した
|
is |
レポートが保存されているかどうかを確認します。 |
is |
指定した
|
is |
指定した
|
is |
指定した
|
log(string) |
|
parse |
|
parse |
安定性: 1.1 - アクティブな開発
|
promisify((callback: (err?: any) => void) => void) | |
promisify(Function) | |
promisify<T1, T2, T3, T4, T5, TResult>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void) | |
promisify<T1, T2, T3, T4, T5>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void) | |
promisify<T1, T2, T3, T4, TResult>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void) | |
promisify<T1, T2, T3, T4>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void) | |
promisify<T1, T2, T3, TResult>((arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void) | |
promisify<T1, T2, T3>((arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void) | |
promisify<T1, T2, TResult>((arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void) | |
promisify<T1, T2>((arg1: T1, arg2: T2, callback: (err?: any) => void) => void) | |
promisify<T1, TResult>((arg1: T1, callback: (err: any, result: TResult) => void) => void) | |
promisify<T1>((arg1: T1, callback: (err?: any) => void) => void) | |
promisify<TCustom>(Custom |
一般的なエラー優先コールバック スタイル (つまり、最後の引数として
または、同じ方法で
|
promisify<TResult>((callback: (err: any, result: TResult) => void) => void) | |
raise |
指定した HTML 要素のイベント データを含むカスタム イベントを発生させます。 |
remove<T>((x: T) => boolean, T[]) | |
strip |
ANSI エスケープ コードが削除された
|
style |
この関数は、ターミナルで印刷するために渡された
書式の配列を渡す場合、適用される書式の順序は左から右に移動するため、次のスタイルによって前のスタイルが上書きされる可能性があります。
形式の完全な一覧は、 |
to |
サロゲート コード ポイント (または同等に、ペアになっていないサロゲート コード 単位) を Unicode の "置換文字" U+FFFD に置き換えた後の |
transferable |
|
transferable |
指定された
|
関数の詳細
aborted(AbortSignal, any)
指定された signal
で中止イベントをリッスンし、signal
が中止されたときに解決される promise を返します。
resource
指定すると、操作に関連付けられているオブジェクトが弱く参照されるため、resource
が中止される前に signal
がガベージ コレクションされた場合、返された promise は保留中のままとなります。
これにより、実行時間の長い操作または取り消し不可能な操作でのメモリ リークを防ぐことができます。
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.
});
function aborted(signal: AbortSignal, resource: any): Promise<void>
パラメーター
- signal
-
AbortSignal
- resource
-
any
中止可能な操作に関連付けられ、弱く保持されている null 以外のオブジェクト。
resource
が中止される前に signal
がガベージ コレクションされた場合、promise は保留中のままになり、Node.js はその追跡を停止できます。
これは、実行時間の長い操作または取り消し不可能な操作でのメモリ リークを防ぐのに役立ちます。
戻り値
Promise<void>
addParamToUrl(string, string, string)
指定された URL にパラメーターを追加します
function addParamToUrl(url: string, paramName: string, value: string): string
パラメーター
- url
-
string
- paramName
-
string
- value
-
string
戻り値
string
assign(any[])
列挙可能なすべてのプロパティの値を 1 つ以上のソース オブジェクトからターゲット オブジェクトにコピーし、ターゲット オブジェクトを返します。
function assign(args: any[]): any
パラメーター
- args
-
any[]
戻り値
any
autoAuthInEmbedUrl(string)
埋め込み URL に autoAuth=true が含まれているかどうかを確認します。
function autoAuthInEmbedUrl(embedUrl: string): boolean
パラメーター
- embedUrl
-
string
戻り値
boolean
callbackify(() => Promise<void>)
async
関数 (または Promise
を返す関数) を受け取り、エラー優先のコールバック スタイルに従って関数を返します。つまり、最後の引数として (err, value) => ...
コールバックを受け取ります。 コールバックでは、最初の引数が拒否理由 (または null
解決された場合は Promise
) になり、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);
});
次の内容が出力されます。
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
});
function callbackify(fn: () => Promise<void>): (callback: (err: NodeJS.ErrnoException) => void) => void
パラメーター
- fn
-
() => Promise<void>
async
関数
戻り値
(callback: (err: NodeJS.ErrnoException) => void) => void
コールバック スタイル関数
callbackify<T1, T2, T3, T4, T5, T6, TResult>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<TResult>)
function callbackify<T1, T2, T3, T4, T5, T6, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void
パラメーター
- fn
-
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<TResult>
戻り値
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void
callbackify<T1, T2, T3, T4, T5, T6>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<void>)
function callbackify<T1, T2, T3, T4, T5, T6>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void
パラメーター
- fn
-
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<void>
戻り値
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void
callbackify<T1, T2, T3, T4, T5, TResult>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>)
function callbackify<T1, T2, T3, T4, T5, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void
パラメーター
- fn
-
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>
戻り値
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void
callbackify<T1, T2, T3, T4, T5>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>)
function callbackify<T1, T2, T3, T4, T5>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void
パラメーター
- fn
-
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>
戻り値
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void
callbackify<T1, T2, T3, T4, TResult>((arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>)
function callbackify<T1, T2, T3, T4, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void
パラメーター
- fn
-
(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>
戻り値
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void
callbackify<T1, T2, T3, T4>((arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>)
function callbackify<T1, T2, T3, T4>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void
パラメーター
- fn
-
(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>
戻り値
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void
callbackify<T1, T2, T3, TResult>((arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>)
function callbackify<T1, T2, T3, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void
パラメーター
- fn
-
(arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>
戻り値
(arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void
callbackify<T1, T2, T3>((arg1: T1, arg2: T2, arg3: T3) => Promise<void>)
function callbackify<T1, T2, T3>(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void
パラメーター
- fn
-
(arg1: T1, arg2: T2, arg3: T3) => Promise<void>
戻り値
(arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void
callbackify<T1, T2, TResult>((arg1: T1, arg2: T2) => Promise<TResult>)
function callbackify<T1, T2, TResult>(fn: (arg1: T1, arg2: T2) => Promise<TResult>): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void
パラメーター
- fn
-
(arg1: T1, arg2: T2) => Promise<TResult>
戻り値
(arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void
callbackify<T1, T2>((arg1: T1, arg2: T2) => Promise<void>)
function callbackify<T1, T2>(fn: (arg1: T1, arg2: T2) => Promise<void>): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void
パラメーター
- fn
-
(arg1: T1, arg2: T2) => Promise<void>
戻り値
(arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void
callbackify<T1, TResult>((arg1: T1) => Promise<TResult>)
function callbackify<T1, TResult>(fn: (arg1: T1) => Promise<TResult>): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void
パラメーター
- fn
-
(arg1: T1) => Promise<TResult>
戻り値
(arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void
callbackify<T1>((arg1: T1) => Promise<void>)
function callbackify<T1>(fn: (arg1: T1) => Promise<void>): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void
パラメーター
- fn
-
(arg1: T1) => Promise<void>
戻り値
(arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void
callbackify<TResult>(() => Promise<TResult>)
function callbackify<TResult>(fn: () => Promise<TResult>): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void
パラメーター
- fn
-
() => Promise<TResult>
戻り値
(callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void
createRandomString()
ランダムな 5 ~ 6 文字の文字列を生成します。
function createRandomString(): string
戻り値
string
debuglog(string, (fn: DebugLoggerFunction) => void)
util.debuglog()
メソッドを使用して、NODE_DEBUG
環境変数の存在に基づいてデバッグ メッセージをstderr
に条件付きで書き込む関数を作成します。
section
名がその環境変数の値内に表示される場合、返される関数は console.error()
と同様に動作します。 そうでない場合、返される関数は no-opです。
import { debuglog } from '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);
環境内で 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;
});
function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger
パラメーター
- section
-
string
debuglog
関数が作成されているアプリケーションの部分を識別する文字列。
- callback
-
(fn: DebugLoggerFunction) => void
より最適化されたログ関数である関数引数を使用してログ関数が初めて呼び出されたときに呼び出されたコールバック。
戻り値
ログ関数
deprecate<T>(T, string, string)
util.deprecate()
メソッドは、fn
(関数またはクラスである可能性があります) を、非推奨としてマークされるようにラップします。
import { deprecate } from 'node:util';
export const obsoleteFunction = deprecate(() => {
// Do something here.
}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');
呼び出されると、util.deprecate()
は、DeprecationWarning
イベントを使用して 'warning'
を出力する関数を返します。 警告が出力され、返された関数が初めて呼び出 stderr
に出力されます。 警告が生成されると、ラップされた関数は警告を生成せずに呼び出されます。
code
の複数の呼び出しで同じ省略可能な util.deprecate()
が指定されている場合、警告はその code
に対して 1 回だけ出力されます。
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 code
--trace-deprecation
または --trace-warnings
コマンド ライン フラグが設定されている場合、または process.traceDeprecation
プロパティが true
に設定されている場合は、非推奨の関数が初めて呼び出されるときに警告とスタック トレースが stderr
に出力されます。
--throw-deprecation
コマンド ライン フラグが設定されている場合、または process.throwDeprecation
プロパティが true
に設定されている場合は、非推奨の関数が呼び出されたときに例外がスローされます。
--throw-deprecation
コマンド ライン フラグと process.throwDeprecation
プロパティは、--trace-deprecation
と process.traceDeprecation
よりも優先されます。
function deprecate<T>(fn: T, msg: string, code?: string): T
パラメーター
- fn
-
T
非推奨となる関数。
- msg
-
string
非推奨の関数が呼び出されたときに表示される警告メッセージ。
- code
-
string
非推奨コード。 コードの一覧については、list of deprecated APIs
を参照してください。
戻り値
T
非推奨の関数は、警告を出力するためにラップされました。
diff(string | (readonly string[]), string | (readonly string[]))
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'));
// []
function diff(actual: string | (readonly string[]), expected: string | (readonly string[])): DiffEntry[]
パラメーター
- actual
-
string | (readonly string[])
比較する最初の値
- expected
-
string | (readonly string[])
比較する 2 番目の値
戻り値
差分エントリの配列。 各エントリは、2 つの要素を持つ配列です。
- インデックス 0:
number
操作コード: 削除用の-1
、no-op/unchanged の0
、挿入用の1
- インデックス 1:
string
操作に関連付けられている値
find<T>((x: T) => boolean, T[])
指定した述語と一致する配列内の最初の値を検索します。
function find<T>(predicate: (x: T) => boolean, xs: T[]): T
パラメーター
- predicate
-
(x: T) => boolean
- xs
-
T[]
戻り値
T
findIndex<T>((x: T) => boolean, T[])
指定した述語と一致する配列内の最初の値のインデックスを検索します。
function findIndex<T>(predicate: (x: T) => boolean, xs: T[]): number
パラメーター
- predicate
-
(x: T) => boolean
- xs
-
T[]
戻り値
number
format(any, any[])
util.format()
メソッドは、0 個以上の書式指定子を含むことができる printf
のような書式指定文字列として、最初の引数を使用して書式設定された文字列を返します。 各指定子は、対応する引数から変換された値に置き換えられます。 サポートされている指定子は次のとおりです。
指定子に対応する引数がない場合は、置き換えされません。
util.format('%s:%s', 'foo');
// Returns: 'foo:%s'
書式指定文字列の一部ではない値は、型が util.inspect()
されていない場合、string
を使用して書式設定されます。
指定子の数よりも多くの引数が 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()
は、デバッグ ツールとして使用される同期メソッドです。
一部の入力値には、イベント ループをブロックする可能性のあるパフォーマンス オーバーヘッドが大きくなる可能性があります。 この関数は注意して使用します。ホット コード パスには使用しないでください。
function format(format?: any, param: any[]): string
パラメーター
- format
-
any
printf
のような書式指定文字列。
- param
-
any[]
戻り値
string
formatWithOptions(InspectOptions, any, any[])
この関数は、
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.
function formatWithOptions(inspectOptions: InspectOptions, format?: any, param: any[]): string
パラメーター
- inspectOptions
- InspectOptions
- format
-
any
- param
-
any[]
戻り値
string
generateUUID()
20 文字の uuid を生成します。
function generateUUID(): string
戻り値
string
getCallSites(GetCallSitesOptions)
function getCallSites(options: GetCallSitesOptions): CallSiteObject[]
パラメーター
- options
-
GetCallSitesOptions
戻り値
getCallSites(number, GetCallSitesOptions)
呼び出し元関数のスタックを含む呼び出しサイト オブジェクトの配列を返します。
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();
オプション sourceMap
を true
に設定することで、元の場所を再構築することができます。
ソース マップが使用できない場合、元の場所は現在の場所と同じになります。
--enable-source-maps
を使用する場合など、--experimental-transform-types
フラグが有効になっている場合、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
function getCallSites(frameCount?: number, options?: GetCallSitesOptions): CallSiteObject[]
パラメーター
- frameCount
-
number
呼び出しサイト オブジェクトとしてキャプチャするフレームの数。
既定値:10
. 許容範囲は 1 ~ 200 です。
- options
-
GetCallSitesOptions
戻り値
呼び出しサイト オブジェクトの配列
getRandomValue()
乱数を返します。
function getRandomValue(): number
戻り値
number
getSystemErrorMap()
Node.js API から使用可能なすべてのシステム エラー コードのマップを返します。
エラー コードとエラー名の間のマッピングはプラットフォームに依存します。
一般的なエラーの名前については、Common System Errors
を参照してください。
fs.access('file/that/does/not/exist', (err) => {
const errorMap = util.getSystemErrorMap();
const name = errorMap.get(err.errno);
console.error(name); // ENOENT
});
function getSystemErrorMap(): Map<number, [string, string]>
戻り値
Map<number, [string, string]>
getSystemErrorMessage(number)
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
});
function getSystemErrorMessage(err: number): string
パラメーター
- err
-
number
戻り値
string
getSystemErrorName(number)
Node.js API から取得された数値エラー コードの文字列名を返します。
エラー コードとエラー名の間のマッピングはプラットフォームに依存します。
一般的なエラーの名前については、Common System Errors
を参照してください。
fs.access('file/that/does/not/exist', (err) => {
const name = util.getSystemErrorName(err.errno);
console.error(name); // ENOENT
});
function getSystemErrorName(err: number): string
パラメーター
- err
-
number
戻り値
string
getTimeDiffInMilliseconds(Date, Date)
2 つの日付間の時間間隔をミリ秒単位で返します。
function getTimeDiffInMilliseconds(start: Date, end: Date): number
パラメーター
- start
-
Date
- end
-
Date
戻り値
number
inherits(unknown, unknown)
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');
function inherits(constructor: unknown, superConstructor: unknown)
パラメーター
- constructor
-
unknown
- superConstructor
-
unknown
inspect(any, boolean, null | number, boolean)
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] {}'
循環参照は、参照インデックスを使用してアンカーを指します。
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] }
// }
次の例では、util
オブジェクトのすべてのプロパティを調べます。
import util from '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.
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 } }
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 }),
);
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_45
util.inspect()
は、デバッグを目的とした同期メソッドです。 最大出力長は約 128 MiB です。 出力が長くなる入力は切り捨てられます。
function inspect(object: any, showHidden?: boolean, depth?: null | number, color?: boolean): string
パラメーター
- object
-
any
任意の JavaScript プリミティブまたは Object
。
- showHidden
-
boolean
- depth
-
null | number
- color
-
boolean
戻り値
string
object
の表現。
inspect(any, InspectOptions)
function inspect(object: any, options?: InspectOptions): string
パラメーター
- object
-
any
- options
- InspectOptions
戻り値
string
isArray(unknown)
警告
この API は非推奨になりました。
Since v4.0.0 - Use isArray
instead.
Array.isArray()
のエイリアス。
指定した true
が object
の場合は、Array
を返します。 それ以外の場合、false
を返します。
import util from 'node:util';
util.isArray([]);
// Returns: true
util.isArray(new Array());
// Returns: true
util.isArray({});
// Returns: false
function isArray(object: unknown): object
パラメーター
- object
-
unknown
戻り値
object
isBoolean(unknown)
警告
この API は非推奨になりました。
Since v4.0.0 - Use typeof value === 'boolean'
instead.
指定した true
が object
の場合は、Boolean
を返します。 それ以外の場合、false
を返します。
import util from 'node:util';
util.isBoolean(1);
// Returns: false
util.isBoolean(0);
// Returns: false
util.isBoolean(false);
// Returns: true
function isBoolean(object: unknown): object
パラメーター
- object
-
unknown
戻り値
object
isBuffer(unknown)
警告
この API は非推奨になりました。
Since v4.0.0 - Use isBuffer
instead.
指定した true
が object
の場合は、Buffer
を返します。 それ以外の場合、false
を返します。
import util from 'node:util';
util.isBuffer({ length: 0 });
// Returns: false
util.isBuffer([]);
// Returns: false
util.isBuffer(Buffer.from('hello world'));
// Returns: true
function isBuffer(object: unknown): object
パラメーター
- object
-
unknown
戻り値
object
isCreate(string)
埋め込み型が作成用であるかどうかを確認します
function isCreate(embedType: string): boolean
パラメーター
- embedType
-
string
戻り値
boolean
isDate(unknown)
指定した true
が object
の場合は、Date
を返します。 それ以外の場合、false
を返します。
import util from 'node:util';
util.isDate(new Date());
// Returns: true
util.isDate(Date());
// false (without 'new' returns a String)
util.isDate({});
// Returns: false
function isDate(object: unknown): object
パラメーター
- object
-
unknown
戻り値
object
isDeepStrictEqual(unknown, unknown)
true
と val1
の間に厳密な等価性が深い場合は、val2
を返します。
それ以外の場合、false
を返します。
詳細な厳密な等価性の詳細については、assert.deepStrictEqual()
を参照してください。
function isDeepStrictEqual(val1: unknown, val2: unknown): boolean
パラメーター
- val1
-
unknown
- val2
-
unknown
戻り値
boolean
isError(unknown)
指定した true
が object
の場合は、Error
を返します。 それ以外の場合、false
を返します。
import util from '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
を操作すると、正しくない結果が得られます。
import util from 'node:util';
const obj = { name: 'Error', message: 'an error occurred' };
util.isError(obj);
// Returns: false
obj[Symbol.toStringTag] = 'Error';
util.isError(obj);
// Returns: true
function isError(object: unknown): object
パラメーター
- object
-
unknown
戻り値
object
isFunction(unknown)
警告
この API は非推奨になりました。
Since v4.0.0 - Use typeof value === 'function'
instead.
指定した true
が object
の場合は、Function
を返します。 それ以外の場合、false
を返します。
import util from 'node:util';
function Foo() {}
const Bar = () => {};
util.isFunction({});
// Returns: false
util.isFunction(Foo);
// Returns: true
util.isFunction(Bar);
// Returns: true
function isFunction(object: unknown): boolean
パラメーター
- object
-
unknown
戻り値
boolean
isNull(unknown)
警告
この API は非推奨になりました。
Since v4.0.0 - Use value === null
instead.
指定された true
が厳密に object
場合は、null
を返します。 それ以外の場合は、false
を返します。
import util from 'node:util';
util.isNull(0);
// Returns: false
util.isNull(undefined);
// Returns: false
util.isNull(null);
// Returns: true
function isNull(object: unknown): object
パラメーター
- object
-
unknown
戻り値
object
isNullOrUndefined(unknown)
警告
この API は非推奨になりました。
Since v4.0.0 - Use value === undefined || value === null
instead.
指定した true
が object
または null
場合に undefined
を返します。 それ以外の場合、false
を返します。
import util from 'node:util';
util.isNullOrUndefined(0);
// Returns: false
util.isNullOrUndefined(undefined);
// Returns: true
util.isNullOrUndefined(null);
// Returns: true
function isNullOrUndefined(object: unknown): object
パラメーター
- object
-
unknown
戻り値
object
isNumber(unknown)
警告
この API は非推奨になりました。
Since v4.0.0 - Use typeof value === 'number'
instead.
指定した true
が object
の場合は、Number
を返します。 それ以外の場合、false
を返します。
import util from 'node:util';
util.isNumber(false);
// Returns: false
util.isNumber(Infinity);
// Returns: true
util.isNumber(0);
// Returns: true
util.isNumber(NaN);
// Returns: true
function isNumber(object: unknown): object
パラメーター
- object
-
unknown
戻り値
object
isObject(unknown)
警告
この API は非推奨になりました。
Since v4.0.0 - Use value !== null && typeof value === 'object'
instead.
指定した true
が厳密に object
であり、Object
ではない場合 (関数が JavaScript のオブジェクトであっても) 場合は、Function
を返します。
それ以外の場合、false
を返します。
import util from 'node:util';
util.isObject(5);
// Returns: false
util.isObject(null);
// Returns: false
util.isObject({});
// Returns: true
util.isObject(() => {});
// Returns: false
function isObject(object: unknown): boolean
パラメーター
- object
-
unknown
戻り値
boolean
isPrimitive(unknown)
警告
この API は非推奨になりました。
Since v4.0.0 - Use (typeof value !== 'object' && typeof value !== 'function') || value === null
instead.
指定した true
がプリミティブ型の場合は、object
を返します。 それ以外の場合は、false
を返します。
import util from '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
function isPrimitive(object: unknown): boolean
パラメーター
- object
-
unknown
戻り値
boolean
isRDLEmbed(string)
埋め込み URL が RDL レポート用であるかどうかを確認します。
function isRDLEmbed(embedUrl: string): boolean
パラメーター
- embedUrl
-
string
戻り値
boolean
isRegExp(unknown)
警告
この API は非推奨になりました。
Since v4.0.0 - Deprecated
指定した true
が object
の場合は、RegExp
を返します。 それ以外の場合、false
を返します。
import util from 'node:util';
util.isRegExp(/some regexp/);
// Returns: true
util.isRegExp(new RegExp('another regexp'));
// Returns: true
util.isRegExp({});
// Returns: false
function isRegExp(object: unknown): object
パラメーター
- object
-
unknown
戻り値
object
isSavedInternal(HttpPostMessage, string, Window)
レポートが保存されているかどうかを確認します。
function isSavedInternal(hpm: HttpPostMessage, uid: string, contentWindow: Window): Promise<boolean>
パラメーター
- hpm
-
HttpPostMessage
- uid
-
string
- contentWindow
-
Window
戻り値
Promise<boolean>
isString(unknown)
警告
この API は非推奨になりました。
Since v4.0.0 - Use typeof value === 'string'
instead.
指定した true
が object
の場合は、string
を返します。 それ以外の場合、false
を返します。
import util from 'node:util';
util.isString('');
// Returns: true
util.isString('foo');
// Returns: true
util.isString(String('foo'));
// Returns: true
util.isString(5);
// Returns: false
function isString(object: unknown): object
パラメーター
- object
-
unknown
戻り値
object
isSymbol(unknown)
警告
この API は非推奨になりました。
Since v4.0.0 - Use typeof value === 'symbol'
instead.
指定した true
が object
の場合は、Symbol
を返します。 それ以外の場合、false
を返します。
import util from 'node:util';
util.isSymbol(5);
// Returns: false
util.isSymbol('foo');
// Returns: false
util.isSymbol(Symbol('foo'));
// Returns: true
function isSymbol(object: unknown): object
パラメーター
- object
-
unknown
戻り値
object
isUndefined(unknown)
警告
この API は非推奨になりました。
Since v4.0.0 - Use value === undefined
instead.
指定した true
が object
されている場合は、undefined
を返します。 それ以外の場合、false
を返します。
import util from 'node:util';
const foo = undefined;
util.isUndefined(5);
// Returns: false
util.isUndefined(foo);
// Returns: true
util.isUndefined(null);
// Returns: false
function isUndefined(object: unknown): object
パラメーター
- object
-
unknown
戻り値
object
log(string)
警告
この API は非推奨になりました。
Since v6.0.0 - Use a third party module instead.
util.log()
メソッドは、指定された string
を出力し、タイムスタンプを含む stdout
します。
import util from 'node:util';
util.log('Timestamped message.');
function log(string: string)
パラメーター
- string
-
string
parseArgs<T>(T)
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' } []
function parseArgs<T>(config?: T): ParsedResults<T>
パラメーター
- config
-
T
解析の引数を指定し、パーサーを構成するために使用します。
config
では、次のプロパティがサポートされています。
戻り値
ParsedResults<T>
解析されたコマンド ライン引数:
parseEnv(string)
安定性: 1.1 - アクティブな開発 .env
ファイルの例を考えると:
import { parseEnv } from 'node:util';
parseEnv('HELLO=world\nHELLO=oh my\n');
// Returns: { HELLO: 'oh my' }
function parseEnv(content: string): object
パラメーター
- content
-
string
.env
ファイルの生の内容。
戻り値
object
promisify((callback: (err?: any) => void) => void)
function promisify(fn: (callback: (err?: any) => void) => void): () => Promise<void>
パラメーター
- fn
-
(callback: (err?: any) => void) => void
戻り値
() => Promise<void>
promisify(Function)
function promisify(fn: Function): Function
パラメーター
- fn
-
Function
戻り値
Function
promisify<T1, T2, T3, T4, T5, TResult>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void)
function promisify<T1, T2, T3, T4, T5, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>
パラメーター
- fn
-
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void
戻り値
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>
promisify<T1, T2, T3, T4, T5>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void)
function promisify<T1, T2, T3, T4, T5>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>
パラメーター
- fn
-
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void
戻り値
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>
promisify<T1, T2, T3, T4, TResult>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void)
function promisify<T1, T2, T3, T4, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>
パラメーター
- fn
-
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void
戻り値
(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>
promisify<T1, T2, T3, T4>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void)
function promisify<T1, T2, T3, T4>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>
パラメーター
- fn
-
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void
戻り値
(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>
promisify<T1, T2, T3, TResult>((arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void)
function promisify<T1, T2, T3, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>
パラメーター
- fn
-
(arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void
戻り値
(arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>
promisify<T1, T2, T3>((arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void)
function promisify<T1, T2, T3>(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise<void>
パラメーター
- fn
-
(arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void
戻り値
(arg1: T1, arg2: T2, arg3: T3) => Promise<void>
promisify<T1, T2, TResult>((arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void)
function promisify<T1, T2, TResult>(fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise<TResult>
パラメーター
- fn
-
(arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void
戻り値
(arg1: T1, arg2: T2) => Promise<TResult>
promisify<T1, T2>((arg1: T1, arg2: T2, callback: (err?: any) => void) => void)
function promisify<T1, T2>(fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2) => Promise<void>
パラメーター
- fn
-
(arg1: T1, arg2: T2, callback: (err?: any) => void) => void
戻り値
(arg1: T1, arg2: T2) => Promise<void>
promisify<T1, TResult>((arg1: T1, callback: (err: any, result: TResult) => void) => void)
function promisify<T1, TResult>(fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void): (arg1: T1) => Promise<TResult>
パラメーター
- fn
-
(arg1: T1, callback: (err: any, result: TResult) => void) => void
戻り値
(arg1: T1) => Promise<TResult>
promisify<T1>((arg1: T1, callback: (err?: any) => void) => void)
function promisify<T1>(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise<void>
パラメーター
- fn
-
(arg1: T1, callback: (err?: any) => void) => void
戻り値
(arg1: T1) => Promise<void>
promisify<TCustom>(CustomPromisify<TCustom>)
一般的なエラー優先コールバック スタイル (つまり、最後の引数として (err, value) => ...
コールバックを受け取る) に続く関数を受け取り、promise を返すバージョンを返します。
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.
});
または、同じ方法で async function
s を使用します。
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();
original[util.promisify.custom]
プロパティが存在する場合、promisify
はその値を返します。カスタムのプロミス関数を参照してください。
promisify()
は、original
は、すべてのケースでコールバックを最終的な引数として受け取る関数であることを前提としています。
original
が関数でない場合、promisify()
はエラーをスローします。
original
が関数であり、その最後の引数がエラー優先コールバックでない場合でも、最後の引数としてエラー優先コールバックが渡されます。
promisify()
を使用するクラス メソッドまたはその他のメソッドに対して this
を使用すると、特別に処理されない限り、期待どおりに動作しない場合があります。
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'
function promisify<TCustom>(fn: CustomPromisify<TCustom>): TCustom
パラメーター
- fn
-
CustomPromisify<TCustom>
戻り値
TCustom
promisify<TResult>((callback: (err: any, result: TResult) => void) => void)
function promisify<TResult>(fn: (callback: (err: any, result: TResult) => void) => void): () => Promise<TResult>
パラメーター
- fn
-
(callback: (err: any, result: TResult) => void) => void
戻り値
() => Promise<TResult>
raiseCustomEvent(HTMLElement, string, any)
指定した HTML 要素のイベント データを含むカスタム イベントを発生させます。
function raiseCustomEvent(element: HTMLElement, eventName: string, eventData: any)
パラメーター
- element
-
HTMLElement
- eventName
-
string
- eventData
-
any
remove<T>((x: T) => boolean, T[])
function remove<T>(predicate: (x: T) => boolean, xs: T[])
パラメーター
- predicate
-
(x: T) => boolean
- xs
-
T[]
stripVTControlCharacters(string)
ANSI エスケープ コードが削除された str
を返します。
console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m'));
// Prints "value"
function stripVTControlCharacters(str: string): string
パラメーター
- str
-
string
戻り値
string
styleText(ForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[], string)
この関数は、ターミナルで印刷するために渡された format
を考慮して書式設定されたテキストを返します。 ターミナルの機能を認識し、 NO_COLORS
、 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);
util.inspect.colors
には、italic
や underline
などのテキスト形式も用意されており、次の両方を組み合わせることができます。
console.log(
util.styleText(['underline', 'italic'], 'My italic underlined message'),
);
書式の配列を渡す場合、適用される書式の順序は左から右に移動するため、次のスタイルによって前のスタイルが上書きされる可能性があります。
console.log(
util.styleText(['red', 'green'], 'text'), // green
);
形式の完全な一覧は、
function styleText(format: ForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[], text: string): string
パラメーター
- format
-
ForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[]
util.inspect.colors
で定義されたテキスト形式またはテキスト形式の配列。
- text
-
string
書式設定するテキスト。
戻り値
string
toUSVString(string)
サロゲート コード ポイント (または同等に、ペアになっていないサロゲート コード 単位) を Unicode の "置換文字" U+FFFD に置き換えた後の string
を返します。
function toUSVString(string: string): string
パラメーター
- string
-
string
戻り値
string
transferableAbortController()
AbortController
が転送可能としてマークされ、AbortSignal
または structuredClone()
で使用できる postMessage()
インスタンスを作成して返します。
function transferableAbortController(): AbortController
戻り値
AbortController
転送可能な AbortController
transferableAbortSignal(AbortSignal)
指定された AbortSignal
を転送可能としてマークして、structuredClone()
および postMessage()
で使用できるようにします。
const signal = transferableAbortSignal(AbortSignal.timeout(100));
const channel = new MessageChannel();
channel.port2.postMessage(signal, [signal]);
function transferableAbortSignal(signal: AbortSignal): AbortSignal
パラメーター
- signal
-
AbortSignal
The AbortSignal
戻り値
AbortSignal
同じ AbortSignal