共用方式為


util module

node:util 模組支援 Node.js 內部 API 的需求。 許多公用程式也適用於應用程式和模塊開發人員。 若要存取它:

import util from 'node:util';

請參閱來源

類別

MIMEParams

MIMEParams API 提供 MIMEType參數的讀取和寫入許可權。

MIMEType

MIMEType 類別的實作

根據瀏覽器慣例,MIMEType 物件的所有屬性都會在類別原型上實作為 getter 和 setter,而不是做為物件本身的數據屬性。

MIME 字串是包含多個有意義元件的結構化字串。 剖析時,會傳回 MIMEType 物件,其中包含每個元件的屬性。

TextDecoder

WHATWG 編碼標準TextDecoder API 的實作。

const decoder = new TextDecoder();
const u8arr = new Uint8Array([72, 101, 108, 108, 111]);
console.log(decoder.decode(u8arr)); // Hello
TextEncoder

WHATWG 編碼標準TextEncoder API 的實作。 TextEncoder 的所有實例都只支援UTF-8編碼。

const encoder = new TextEncoder();
const uint8array = encoder.encode('this is some data');

全域物件上也提供 TextEncoder 類別。

介面

CallSiteObject
CustomPromisifyLegacy
CustomPromisifySymbol
DebugLogger
EncodeIntoResult
InspectOptions
InspectOptionsStylized
IsDeepStrictEqualOptions
ParseArgsConfig
ParseArgsOptionDescriptor
ParseArgsOptionsConfig
StyleTextOptions

類型別名

CustomInspectFunction
CustomPromisify
DebugLoggerFunction
DiffEntry
ParseArgsOptionsType

parseArgs 中使用的自變數類型。

Style

函式

aborted(AbortSignal, any)

接聽所提供 signal 上的中止事件,並傳回在中止 signal 時解析的承諾。 如果提供 resource,它會弱式參考作業的相關物件,因此,如果在 resource 中止之前垃圾收集 signal,則傳回的承諾應維持擱置中。 這可防止長時間執行或不可取消的作業中記憶體流失。

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.
});
addParamToUrl(string, string, string)

將參數新增至指定的 URL

assign(any[])

將所有可列舉屬性的值從一或多個來源物件複製到目標物件,並傳回目標物件。

autoAuthInEmbedUrl(string)

檢查內嵌 URL 是否包含 autoAuth=true。

callbackify(() => Promise<void>)

採用 async 函式(或傳回 Promise的函式),並在錯誤優先回呼樣式之後傳回函式,也就是以 (err, value) => ... 回呼作為最後一個自變數。 在回呼中,第一個自變數將是拒絕原因(如果已解析 null,則為 Promise),而第二個自變數將是解析的值。

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
});
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>)
createRandomString()

產生隨機 5 到 6 個字元字串。

debuglog(string, (fn: DebugLoggerFunction) => void)

方法util.debuglog()可用來建立函式,根據環境變數的存在,有條件地寫入偵stderr錯訊息NODE_DEBUG。 如果 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 是進程標識碼。如果未使用該環境變數集執行,則不會列印任何專案。

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]

環境變數中section可以指定多個逗號分隔NODE_DEBUG名稱: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;
});
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發出警告一次。

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

如果使用 --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-deprecationprocess.traceDeprecation

diff(string | (readonly string[]), string | (readonly string[]))

util.diff() 比較兩個字串或陣列值,並傳回差異項目的陣列。 它會使用 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'));
// []
find<T>((x: T) => boolean, T[])

尋找陣列中符合指定述詞的第一個值。

findIndex<T>((x: T) => boolean, T[])

尋找陣列中符合指定述詞之第一個值的索引。

format(any, any[])

util.format() 方法會使用第一個自變數作為 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(),則會傳回,因為它沒有任何格式設定:

util.format('%% %s');
// Returns: '%% %s'

util.format() 是同步方法,其用途為偵錯工具。 某些輸入值可能會有顯著的效能額外負荷,而可能會封鎖事件迴圈。 請小心使用此函式,且絕不會在經常性程式代碼路徑中使用。

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.
generateUUID()

產生 20 個字元的 uuid。

getCallSites(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();

藉由將 選項設定為 sourceMaptrue,即可重新建構原始位置。 如果來源對應無法使用,原始位置會與目前位置相同。 啟用 --enable-source-maps 旗標時,例如使用 --experimental-transform-types時,預設為 true sourceMap

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
getRandomValue()

傳回隨機數

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
});
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
});
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
});
getTimeDiffInMilliseconds(Date, Date)

以毫秒為單位傳回兩個日期之間的時間間隔

inherits(unknown, unknown)

不建議使用 util.inherits()。 請使用ES6 classextends 關鍵詞來取得語言層級繼承支援。 另請注意,這兩種樣式 語意不相容

將原型方法從一個 建構函式 繼承到另一個建構函式。 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!"

使用 classextends的 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');
inspect(any, boolean, null | number, boolean)

util.inspect() 方法會傳回用於偵錯之 object 的字串表示。 util.inspect 的輸出隨時可能會變更,不應以程序設計方式相依。 可能會傳遞其他 options 來改變結果。 util.inspect() 會使用建構函式的名稱和/或 Symbol.toStringTag 屬性,為檢查的值建立可識別的標籤。

class Foo {
  get [Symbol.toStringTag]() {
    return 'bar';
  }
}

class Bar {}

const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });

util.inspect(new Foo()); // 'Foo [bar] {}'
util.inspect(new Bar()); // 'Bar {}'
util.inspect(baz);       // '[foo] {}'

循環參考會使用參考索引指向其錨點:

import { inspect } from 'node:util';

const obj = {};
obj.a = [obj];
obj.b = {};
obj.b.inner = obj.b;
obj.b.obj = obj;

console.log(inspect(obj));
// <ref *1> {
//   a: [ [Circular *1] ],
//   b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }
// }

下列範例會檢查 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] 選項允許檢查 WeakMapWeakSet 專案。 如果項目數超過 maxArrayLength,則不保證會顯示哪些專案。 這表示擷取相同的 WeakSet 專案兩次可能會導致不同的輸出。 此外,任何沒有剩餘強式參考的項目隨時都可以進行垃圾收集。

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 選項會將底線每三位數新增至所有數位。

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。 會導致輸出較長的輸入將會被截斷。

inspect(any, InspectOptions)
isArray(unknown)

Array.isArray() 的別名。

如果指定的 trueobject,則傳回 Array。 否則傳回 false

import util from 'node:util';

util.isArray([]);
// Returns: true
util.isArray(new Array());
// Returns: true
util.isArray({});
// Returns: false
isCreate(string)

檢查內嵌類型是否為建立

isDeepStrictEqual(unknown, unknown, IsDeepStrictEqualOptions)

如果 trueval1之間有深厚的嚴格相等,則傳回 val2。 否則傳回 false

如需深度嚴格相等的詳細資訊,請參閱 assert.deepStrictEqual()

isRDLEmbed(string)

檢查內嵌 URL 是否為 RDL 報表。

isSavedInternal(HttpPostMessage, string, Window)

檢查報表是否已儲存。

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' } []
parseEnv(string)

穩定性:1.1 - 使用中開發 提供範例 .env 檔案:

import { parseEnv } from 'node:util';

parseEnv('HELLO=world\nHELLO=oh my\n');
// Returns: { HELLO: 'oh my' }
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>(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

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'
promisify<TResult>((callback: (err: any, result: TResult) => void) => void)
raiseCustomEvent(HTMLElement, string, any)

使用指定 HTML 元素上的事件數據引發自訂事件。

remove<T>((x: T) => boolean, T[])
setTraceSigInt(boolean)

啟用或停用在 上 SIGINT列印堆疊追蹤。 API 僅在主執行緒上可用。

stripVTControlCharacters(string)

傳回已移除任何 ANSI 逸出碼的 str

console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m'));
// Prints "value"
styleText(ForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[], string, StyleTextOptions)

此函式會傳回格式化文字, format 以考慮在終端機中列印所傳遞的 。 它知道終端機的功能,並透過和 NO_COLORNODE_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 也提供文字格式,例如 italicunderline,而且您可以合併兩者:

console.log(
  util.styleText(['underline', 'italic'], 'My italic underlined message'),
);

傳遞格式陣列時,套用的格式順序會由左至右,因此下列樣式可能會覆寫前一個格式。

console.log(
  util.styleText(['red', 'green'], 'text'), // green
);

特殊格式值 none 不會將其他樣式套用至文字。

您可以在 修飾詞中找到格式的完整清單,

toUSVString(string)

以 Unicode “replacement character” U+FFFD 取代任何 Surrogate 字碼點之後,傳回 string

transferableAbortController()

建立並傳回 AbortController 實例,其 AbortSignal 標示為可傳輸,且可與 structuredClone()postMessage()搭配使用。

transferableAbortSignal(AbortSignal)

將指定的 AbortSignal 標示為可轉移,以便與structuredClone()postMessage()搭配使用。

const signal = transferableAbortSignal(AbortSignal.timeout(100));
const channel = new MessageChannel();
channel.port2.postMessage(signal, [signal]);

函式詳細資料

aborted(AbortSignal, any)

接聽所提供 signal 上的中止事件,並傳回在中止 signal 時解析的承諾。 如果提供 resource,它會弱式參考作業的相關物件,因此,如果在 resource 中止之前垃圾收集 signal,則傳回的承諾應維持擱置中。 這可防止長時間執行或不可取消的作業中記憶體流失。

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 物件。 如果 resourcesignal 中止之前進行垃圾收集,承諾仍會擱置中,讓 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[])

將所有可列舉屬性的值從一或多個來源物件複製到目標物件,並傳回目標物件。

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),而第二個自變數將是解析的值。

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()可用來建立函式,根據環境變數的存在,有條件地寫入偵stderr錯訊息NODE_DEBUG。 如果 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 是進程標識碼。如果未使用該環境變數集執行,則不會列印任何專案。

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]

環境變數中section可以指定多個逗號分隔NODE_DEBUG名稱: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發出警告一次。

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

如果使用 --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-deprecationprocess.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() 比較兩個字串或陣列值,並傳回差異項目的陣列。 它會使用 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[])

要比較的第二個值

傳回

差異項目的陣列。 每個專案都是具有兩個元素的陣列:

  • 索引 0:作業程式代碼: number-1 用於刪除, 0 針對 no-op/未變更, 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() 方法會使用第一個自變數作為 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(),則會傳回,因為它沒有任何格式設定:

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();

藉由將 選項設定為 sourceMaptrue,即可重新建構原始位置。 如果來源對應無法使用,原始位置會與目前位置相同。 啟用 --enable-source-maps 旗標時,例如使用 --experimental-transform-types時,預設為 true sourceMap

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)

以毫秒為單位傳回兩個日期之間的時間間隔

function getTimeDiffInMilliseconds(start: Date, end: Date): number

參數

start

Date

end

Date

傳回

number

inherits(unknown, unknown)

不建議使用 util.inherits()。 請使用ES6 classextends 關鍵詞來取得語言層級繼承支援。 另請注意,這兩種樣式 語意不相容

將原型方法從一個 建構函式 繼承到另一個建構函式。 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!"

使用 classextends的 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() 會使用建構函式的名稱和/或 Symbol.toStringTag 屬性,為檢查的值建立可識別的標籤。

class Foo {
  get [Symbol.toStringTag]() {
    return 'bar';
  }
}

class Bar {}

const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });

util.inspect(new Foo()); // 'Foo [bar] {}'
util.inspect(new Bar()); // 'Bar {}'
util.inspect(baz);       // '[foo] {}'

循環參考會使用參考索引指向其錨點:

import { inspect } from 'node:util';

const obj = {};
obj.a = [obj];
obj.b = {};
obj.b.inner = obj.b;
obj.b.obj = obj;

console.log(inspect(obj));
// <ref *1> {
//   a: [ [Circular *1] ],
//   b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }
// }

下列範例會檢查 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] 選項允許檢查 WeakMapWeakSet 專案。 如果項目數超過 maxArrayLength,則不保證會顯示哪些專案。 這表示擷取相同的 WeakSet 專案兩次可能會導致不同的輸出。 此外,任何沒有剩餘強式參考的項目隨時都可以進行垃圾收集。

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 選項會將底線每三位數新增至所有數位。

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() 的別名。

如果指定的 trueobject,則傳回 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

isCreate(string)

檢查內嵌類型是否為建立

function isCreate(embedType: string): boolean

參數

embedType

string

傳回

boolean

isDeepStrictEqual(unknown, unknown, IsDeepStrictEqualOptions)

如果 trueval1之間有深厚的嚴格相等,則傳回 val2。 否則傳回 false

如需深度嚴格相等的詳細資訊,請參閱 assert.deepStrictEqual()

function isDeepStrictEqual(val1: unknown, val2: unknown, options?: IsDeepStrictEqualOptions): boolean

參數

val1

unknown

val2

unknown

傳回

boolean

isRDLEmbed(string)

檢查內嵌 URL 是否為 RDL 報表。

function isRDLEmbed(embedUrl: string): boolean

參數

embedUrl

string

傳回

boolean

isSavedInternal(HttpPostMessage, string, Window)

檢查報表是否已儲存。

function isSavedInternal(hpm: HttpPostMessage, uid: string, contentWindow: Window): Promise<boolean>

參數

hpm

HttpPostMessage

uid

string

contentWindow

Window

傳回

Promise<boolean>

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): NodeJS.Dict<string>

參數

content

string

.env 檔案的原始內容。

傳回

NodeJS.Dict<string>

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

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[]

setTraceSigInt(boolean)

啟用或停用在 上 SIGINT列印堆疊追蹤。 API 僅在主執行緒上可用。

function setTraceSigInt(enable: boolean)

參數

enable

boolean

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, StyleTextOptions)

此函式會傳回格式化文字, format 以考慮在終端機中列印所傳遞的 。 它知道終端機的功能,並透過和 NO_COLORNODE_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 也提供文字格式,例如 italicunderline,而且您可以合併兩者:

console.log(
  util.styleText(['underline', 'italic'], 'My italic underlined message'),
);

傳遞格式陣列時,套用的格式順序會由左至右,因此下列樣式可能會覆寫前一個格式。

console.log(
  util.styleText(['red', 'green'], 'text'), // green
);

特殊格式值 none 不會將其他樣式套用至文字。

您可以在 修飾詞中找到格式的完整清單,

function styleText(format: ForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[], text: string, options?: StyleTextOptions): string

參數

format

ForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[]

util.inspect.colors中定義的文字格式或文字格式陣列。

text

string

要格式化的文字。

傳回

string

toUSVString(string)

以 Unicode “replacement character” U+FFFD 取代任何 Surrogate 字碼點之後,傳回 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

中止

傳回

AbortSignal

相同的中止