다음을 통해 공유


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)

embed 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

콜백은 비동기적으로 실행되며 스택 추적이 제한됩니다. 콜백이 throw되면 프로세스가 '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 프로세스 ID입니다. 해당 환경 변수 집합으로 실행되지 않으면 아무것도 인쇄되지 않습니다.

section 와일드카드도 지원합니다.

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

log('hi there, it\'s foo-bar [%d]', 2333);

환경에서 NODE_DEBUG=foo* 함께 실행되면 다음과 같이 출력됩니다.

FOO-BAR 3257: hi there, it's foo-bar [2333]

환경 변수section에는 여러 개의 쉼표로 구분 NODE_DEBUGNODE_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

또는 명령줄 플래그를 사용하거나 속성이 첫 번째 사용 중단 경고로 전에 설정된 경우 메서드는 아무 것도 수행하지 않습니다.

--trace-deprecation 또는 --trace-warnings 명령줄 플래그가 설정되거나 process.traceDeprecation 속성이 true설정되면 사용되지 않는 함수가 처음 호출될 때 stderr 위해 경고 및 스택 추적이 인쇄됩니다.

--throw-deprecation 명령줄 플래그가 설정되었거나 process.throwDeprecation 속성이 true설정되면 사용되지 않는 함수가 호출될 때 예외가 throw됩니다.

--throw-deprecation 명령줄 플래그 및 process.throwDeprecation 속성이 --trace-deprecationprocess.traceDeprecation보다 우선합니다.

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

util.diff() 는 두 문자열 또는 배열 값을 비교하고 차이 항목의 배열을 반환합니다. Myers diff 알고리즘을 사용하여 어설션 오류 메시지에서 내부적으로 사용하는 것과 동일한 알고리즘인 최소한의 차이를 계산합니다.

값이 같으면 빈 배열이 반환됩니다.

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() 메서드는 0개 이상의 형식 지정자를 포함할 수 있는 printf형식 문자열로 첫 번째 인수를 사용하여 형식이 지정된 문자열을 반환합니다. 각 지정자는 해당 인수에서 변환된 값으로 대체됩니다. 지원되는 지정자는 다음과 같습니다.

지정자에 해당 인수가 없으면 대체되지 않습니다.

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

형식 문자열의 일부가 아닌 값은 형식이 util.inspect()않은 경우 string 사용하여 서식이 지정됩니다.

지정자 수보다 더 많은 인수가 util.format() 메서드에 전달되면 추가 인수가 반환된 문자열에 연결되고 공백으로 구분됩니다.

util.format('%s:%s', 'foo', 'bar', 'baz');
// Returns: 'foo:bar baz'

첫 번째 인수에 유효한 형식 지정자가 없는 경우 util.format() 공백으로 구분된 모든 인수의 연결 문자열을 반환합니다.

util.format(1, 2, 3);
// Returns: '1 2 3'

util.format()인수를 하나만 전달하면 서식이 없는 상태로 반환됩니다.

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사용하는 경우) 기본적으로 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). 추가 편의를 위해 superConstructorconstructor.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() 디버깅을 위한 동기 메서드입니다. 최대 출력 길이는 약 128MiB입니다. 출력이 길어지는 입력은 잘립니다.

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)

embed 형식이 만들기용인지 확인합니다.

isDeepStrictEqual(unknown, unknown, IsDeepStrictEqualOptions)

true val1사이에 엄격한 같음이 있으면 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 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_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)

서로게이트 코드 포인트(또는 마찬가지로 20진수 서로게이트 코드 단위)를 유니코드 "대체 문자" 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)

embed 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

콜백은 비동기적으로 실행되며 스택 추적이 제한됩니다. 콜백이 throw되면 프로세스가 '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 프로세스 ID입니다. 해당 환경 변수 집합으로 실행되지 않으면 아무것도 인쇄되지 않습니다.

section 와일드카드도 지원합니다.

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

log('hi there, it\'s foo-bar [%d]', 2333);

환경에서 NODE_DEBUG=foo* 함께 실행되면 다음과 같이 출력됩니다.

FOO-BAR 3257: hi there, it's foo-bar [2333]

환경 변수section에는 여러 개의 쉼표로 구분 NODE_DEBUGNODE_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

또는 명령줄 플래그를 사용하거나 속성이 첫 번째 사용 중단 경고로 전에 설정된 경우 메서드는 아무 것도 수행하지 않습니다.

--trace-deprecation 또는 --trace-warnings 명령줄 플래그가 설정되거나 process.traceDeprecation 속성이 true설정되면 사용되지 않는 함수가 처음 호출될 때 stderr 위해 경고 및 스택 추적이 인쇄됩니다.

--throw-deprecation 명령줄 플래그가 설정되었거나 process.throwDeprecation 속성이 true설정되면 사용되지 않는 함수가 호출될 때 예외가 throw됩니다.

--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 diff 알고리즘을 사용하여 어설션 오류 메시지에서 내부적으로 사용하는 것과 동일한 알고리즘인 최소한의 차이를 계산합니다.

값이 같으면 빈 배열이 반환됩니다.

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() 메서드는 0개 이상의 형식 지정자를 포함할 수 있는 printf형식 문자열로 첫 번째 인수를 사용하여 형식이 지정된 문자열을 반환합니다. 각 지정자는 해당 인수에서 변환된 값으로 대체됩니다. 지원되는 지정자는 다음과 같습니다.

지정자에 해당 인수가 없으면 대체되지 않습니다.

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

형식 문자열의 일부가 아닌 값은 형식이 util.inspect()않은 경우 string 사용하여 서식이 지정됩니다.

지정자 수보다 더 많은 인수가 util.format() 메서드에 전달되면 추가 인수가 반환된 문자열에 연결되고 공백으로 구분됩니다.

util.format('%s:%s', 'foo', 'bar', 'baz');
// Returns: 'foo:bar baz'

첫 번째 인수에 유효한 형식 지정자가 없는 경우 util.format() 공백으로 구분된 모든 인수의 연결 문자열을 반환합니다.

util.format(1, 2, 3);
// Returns: '1 2 3'

util.format()인수를 하나만 전달하면 서식이 없는 상태로 반환됩니다.

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사용하는 경우) 기본적으로 sourceMap true입니다.

import { getCallSites } from 'node:util';

interface Foo {
  foo: string;
}

const callSites = getCallSites({ sourceMap: true });

// With sourceMap:
// Function Name: ''
// Script Name: example.js
// Line Number: 7
// Column Number: 26

// Without sourceMap:
// Function Name: ''
// Script Name: example.js
// Line Number: 2
// Column Number: 26
function getCallSites(frameCount?: number, options?: GetCallSitesOptions): CallSiteObject[]

매개 변수

frameCount

number

호출 사이트 개체로 캡처할 프레임 수입니다. 기본값:10. 허용 범위는 1에서 200 사이입니다.

options

GetCallSitesOptions

반환

호출 사이트 개체의 배열

getRandomValue()

난수를 반환합니다.

function getRandomValue(): number

반환

number

getSystemErrorMap()

Node.js API에서 사용할 수 있는 모든 시스템 오류 코드의 맵을 반환합니다. 오류 코드와 오류 이름 간의 매핑은 플랫폼에 따라 다릅니다. 일반적인 오류의 이름은 Common System Errors 참조하세요.

fs.access('file/that/does/not/exist', (err) => {
  const errorMap = util.getSystemErrorMap();
  const name = errorMap.get(err.errno);
  console.error(name);  // ENOENT
});
function getSystemErrorMap(): Map<number, [string, string]>

반환

Map<number, [string, string]>

getSystemErrorMessage(number)

Node.js API에서 제공되는 숫자 오류 코드에 대한 문자열 메시지를 반환합니다. 오류 코드와 문자열 메시지 간의 매핑은 플랫폼에 따라 다릅니다.

fs.access('file/that/does/not/exist', (err) => {
  const message = util.getSystemErrorMessage(err.errno);
  console.error(message);  // no such file or directory
});
function getSystemErrorMessage(err: number): string

매개 변수

err

number

반환

string

getSystemErrorName(number)

Node.js API에서 가져온 숫자 오류 코드의 문자열 이름을 반환합니다. 오류 코드와 오류 이름 간의 매핑은 플랫폼에 따라 다릅니다. 일반적인 오류의 이름은 Common System Errors 참조하세요.

fs.access('file/that/does/not/exist', (err) => {
  const name = util.getSystemErrorName(err.errno);
  console.error(name);  // ENOENT
});
function getSystemErrorName(err: number): string

매개 변수

err

number

반환

string

getTimeDiffInMilliseconds(Date, Date)

두 날짜 사이의 시간 간격을 밀리초 단위로 반환합니다.

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). 추가 편의를 위해 superConstructorconstructor.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() 디버깅을 위한 동기 메서드입니다. 최대 출력 길이는 약 128MiB입니다. 출력이 길어지는 입력은 잘립니다.

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)

embed 형식이 만들기용인지 확인합니다.

function isCreate(embedType: string): boolean

매개 변수

embedType

string

반환

boolean

isDeepStrictEqual(unknown, unknown, IsDeepStrictEqualOptions)

true val1사이에 엄격한 같음이 있으면 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 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_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: 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)

서로게이트 코드 포인트(또는 마찬가지로 20진수 서로게이트 코드 단위)를 유니코드 "대체 문자" U+FFFD로 바꾼 후 string 반환합니다.

function toUSVString(string: string): string

매개 변수

string

string

반환

string

transferableAbortController()

AbortController 전송 가능으로 표시되고 AbortSignal 또는 structuredClone()함께 사용할 수 있는 postMessage() 인스턴스를 만들고 반환합니다.

function transferableAbortController(): AbortController

반환

AbortController

양도 가능한 AbortController

transferableAbortSignal(AbortSignal)

지정된 AbortSignal 전송 가능으로 표시하여structuredClone()postMessage()사용할 수 있도록 합니다.

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

매개 변수

signal

AbortSignal

The AbortSignal

반환

AbortSignal

동일한 AbortSignal