util module

MIMEParams

MIMEParams API 提供对 MIMEType参数的读取和写入访问权限。

MIMEType

MIMEType 类实现。

根据浏览器约定,MIMEType 对象的所有属性作为类原型上的 getter 和 setter 实现,而不是作为对象本身的数据属性实现。

MIME 字符串是包含多个有意义的组件的结构化字符串。 分析后,将返回一个 MIMEType 对象,其中包含每个组件的属性。

函数

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>)
convertProcessSignalToExitCode(Signals)

该方法 util.convertProcessSignalToExitCode() 将信号名称转换为其相应的 POSIX 退出代码。 在 POSIX 标准之后,由信号终止的进程退出代码将计算为 128 + signal number

如果 signal 不是有效的信号名称,则会引发错误。 请参阅 signal(7) 有效信号列表。

import { convertProcessSignalToExitCode } from 'node:util';

console.log(convertProcessSignalToExitCode('SIGTERM')); // 143 (128 + 15)
console.log(convertProcessSignalToExitCode('SIGKILL')); // 137 (128 + 9)

当使用进程根据终止进程的信号确定退出代码时,这特别有用。

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 是进程 ID。如果未使用该环境变量集运行,则不会打印任何内容。

section 还支持通配符:

import { debuglog } from 'node:util';
const log = debuglog('foo-bar');

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

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

此函数与 格式相同,不同之处在于它采用 inspectOptions 参数,该参数指定传递给 检查的选项。

util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 });
// Returns 'See object { foo: 42 }', where `42` is colored as a number
// when printed to a terminal.
generateUUID()

生成 20 个字符的 uuid。

getCallSites(GetCallSitesOptions)
getCallSites(number, GetCallSitesOptions)

返回包含调用方函数堆栈的调用站点对象的数组。

与访问 a error.stack不同,从此 API 返回的结果不会受到干扰 Error.prepareStackTrace

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.columnNumber}`);
  });
  // 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启用标志后,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
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) => ... 回调作为最后一个参数,并返回返回承诺的版本。

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 functions:

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(InspectColor | (readonly InspectColor[]), string, StyleTextOptions)

此函数返回一个格式化文本,该 format 文本考虑在终端中为打印而传递。 它了解终端的功能,并根据配置集和NO_COLORNODE_DISABLE_COLORSFORCE_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“替换字符”U+FFFD 替换任何代理项码位(或者等效于任何未配对的代理项代码单元)后返回 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 对象,并处于弱中。 如果在 resource 中止之前垃圾回收 signal,承诺将保持挂起状态,从而允许 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

convertProcessSignalToExitCode(Signals)

该方法 util.convertProcessSignalToExitCode() 将信号名称转换为其相应的 POSIX 退出代码。 在 POSIX 标准之后,由信号终止的进程退出代码将计算为 128 + signal number

如果 signal 不是有效的信号名称,则会引发错误。 请参阅 signal(7) 有效信号列表。

import { convertProcessSignalToExitCode } from 'node:util';

console.log(convertProcessSignalToExitCode('SIGTERM')); // 143 (128 + 15)
console.log(convertProcessSignalToExitCode('SIGKILL')); // 137 (128 + 9)

当使用进程根据终止进程的信号确定退出代码时,这特别有用。

function convertProcessSignalToExitCode(signal: Signals): number

参数

signal

Signals

信号名称(例如 'SIGTERM'

返回

number

对应于

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 是进程 ID。如果未使用该环境变量集运行,则不会打印任何内容。

section 还支持通配符:

import { debuglog } from 'node:util';
const log = debuglog('foo-bar');

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

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, options?: DeprecateOptions): 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删除、0no-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[])

此函数与 格式相同,不同之处在于它采用 inspectOptions 参数,该参数指定传递给 检查的选项。

util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 });
// Returns 'See object { foo: 42 }', where `42` is colored as a number
// when printed to a terminal.
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[]

参数

返回

getCallSites(number, GetCallSitesOptions)

返回包含调用方函数堆栈的调用站点对象的数组。

与访问 a error.stack不同,从此 API 返回的结果不会受到干扰 Error.prepareStackTrace

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.columnNumber}`);
  });
  // 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启用标志后,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 之间。

返回

调用网站对象的数组

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) => ... 回调作为最后一个参数,并返回返回承诺的版本。

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 functions:

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(InspectColor | (readonly InspectColor[]), string, StyleTextOptions)

此函数返回一个格式化文本,该 format 文本考虑在终端中为打印而传递。 它了解终端的功能,并根据配置集和NO_COLORNODE_DISABLE_COLORSFORCE_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: InspectColor | (readonly InspectColor[]), text: string, options?: StyleTextOptions): string

参数

format

InspectColor | (readonly InspectColor[])

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

相同的中止

变量详细信息

TextDecoder

TextDecoder: (label?: string, options?: TextDecoderOptions) => TextDecoder

类型

(label?: string, options?: TextDecoderOptions) => TextDecoder

TextEncoder

TextEncoder: () => TextEncoder

类型

() => TextEncoder