Skip to main content
The node:util module provides utility functions that support the needs of Node.js internal APIs. Many of these utilities are useful for application and module developers as well.

Installation

import util from 'node:util';
// or
const util = require('node:util');

Key Functions

util.promisify(original)

Converts a callback-based function to a Promise-based function. Parameters:
  • original - A function following the error-first callback style
Returns: - A Promise-based version of the function Example:
import { promisify } from 'node:util';
import { readFile } from 'node:fs';

const readFileAsync = promisify(readFile);

try {
  const data = await readFileAsync('file.txt', 'utf8');
  console.log(data);
} catch (err) {
  console.error(err);
}

util.callbackify(original)

Converts an async function or Promise-returning function to a callback style function. Parameters:
  • original - An async function or function that returns a Promise
Returns: - A callback style function Example:
import { callbackify } from 'node:util';

async function fetchData() {
  return 'hello world';
}

const callbackFunction = callbackify(fetchData);

callbackFunction((err, result) => {
  if (err) throw err;
  console.log(result); // 'hello world'
});

util.inspect(object[, options])

Returns a string representation of an object for debugging purposes. Parameters:
  • object - The object to inspect
  • options - Optional formatting options
    • showHidden - Show non-enumerable properties (default: false)
    • depth - Recursion depth (default: 2)
    • colors - Colorize output (default: false)
    • compact - Compact output format
    • maxArrayLength - Maximum array elements to show
    • breakLength - Length at which to break output
Returns: - String representation of the object Example:
import { inspect } from 'node:util';

const obj = {
  name: 'John',
  details: { age: 30, city: 'NYC' }
};

console.log(inspect(obj, { depth: null, colors: true }));

util.format(format[, …args])

Returns a formatted string using printf-like format specifiers. Format specifiers:
  • %s - String
  • %d - Number
  • %i - Integer
  • %f - Floating point
  • %j - JSON
  • %o - Object
  • %% - Literal percent sign
Example:
import { format } from 'node:util';

const formatted = format('Hello %s, you are %d years old', 'John', 30);
console.log(formatted); // 'Hello John, you are 30 years old'

util.types

Provides type checking utilities for various JavaScript and Node.js types.

Common Type Checks

import { types } from 'node:util';

// Check if value is a Promise
types.isPromise(Promise.resolve()); // true

// Check if value is async function
types.isAsyncFunction(async () => {}); // true

// Check if value is a Map
types.isMap(new Map()); // true

// Check if value is a Set
types.isSet(new Set()); // true

// Check if value is a Date
types.isDate(new Date()); // true

// Check if value is a RegExp
types.isRegExp(/abc/); // true

// Check typed arrays
types.isUint8Array(new Uint8Array()); // true
types.isArrayBuffer(new ArrayBuffer(8)); // true

Available Type Checks

  • isAnyArrayBuffer(value)
  • isArgumentsObject(value)
  • isArrayBuffer(value)
  • isArrayBufferView(value)
  • isAsyncFunction(value)
  • isBigInt64Array(value)
  • isBigUint64Array(value)
  • isBooleanObject(value)
  • isBoxedPrimitive(value)
  • isDataView(value)
  • isDate(value)
  • isExternal(value)
  • isFloat32Array(value)
  • isFloat64Array(value)
  • isGeneratorFunction(value)
  • isGeneratorObject(value)
  • isInt8Array(value)
  • isInt16Array(value)
  • isInt32Array(value)
  • isMap(value)
  • isMapIterator(value)
  • isModuleNamespaceObject(value)
  • isNativeError(value)
  • isNumberObject(value)
  • isPromise(value)
  • isProxy(value)
  • isRegExp(value)
  • isSet(value)
  • isSetIterator(value)
  • isSharedArrayBuffer(value)
  • isStringObject(value)
  • isSymbolObject(value)
  • isTypedArray(value)
  • isUint8Array(value)
  • isUint8ClampedArray(value)
  • isUint16Array(value)
  • isUint32Array(value)
  • isWeakMap(value)
  • isWeakSet(value)

Debugging Utilities

util.debuglog(section[, callback])

Creates a function that conditionally writes debug messages based on the NODE_DEBUG environment variable. Example:
import { debuglog } from 'node:util';

const log = debuglog('myapp');

log('Starting application [%d]', process.pid);
// Only outputs if NODE_DEBUG=myapp is set
Usage:
NODE_DEBUG=myapp node app.js
# Output: MYAPP 12345: Starting application [12345]

util.deprecate(fn, msg[, code])

Marks a function as deprecated and emits a deprecation warning when called. Example:
import { deprecate } from 'node:util';

export const oldFunction = deprecate(
  () => {
    // Function implementation
  },
  'oldFunction() is deprecated. Use newFunction() instead.',
  'DEP0001'
);

Additional Utilities

util.parseArgs([config])

Parses command-line arguments (Node.js v18.3.0+). Example:
import { parseArgs } from 'node:util';

const options = {
  name: { type: 'string' },
  verbose: { type: 'boolean', short: 'v' }
};

const { values, positionals } = parseArgs({ options });
console.log(values.name);
console.log(values.verbose);

util.stripVTControlCharacters(str)

Removes ANSI escape codes from a string. Example:
import { stripVTControlCharacters } from 'node:util';

const str = '\x1b[31mRed text\x1b[0m';
const plain = stripVTControlCharacters(str);
console.log(plain); // 'Red text'

Common Use Cases

Converting Callback APIs to Promises

import { promisify } from 'node:util';
import { exec } from 'node:child_process';

const execAsync = promisify(exec);

try {
  const { stdout, stderr } = await execAsync('ls -la');
  console.log(stdout);
} catch (error) {
  console.error(error);
}

Deep Object Inspection

import { inspect } from 'node:util';

const complexObject = {
  nested: {
    deep: {
      value: [1, 2, 3],
      map: new Map([['key', 'value']])
    }
  }
};

console.log(inspect(complexObject, {
  depth: Infinity,
  colors: true,
  compact: false
}));

Type Validation

import { types } from 'node:util';

function processData(data) {
  if (types.isPromise(data)) {
    return data.then(processData);
  }
  
  if (types.isTypedArray(data)) {
    // Handle typed array
    return Array.from(data);
  }
  
  return data;
}