{ "type": "module", "source": "doc/api/util.md", "modules": [ { "textRaw": "Util", "name": "util", "introduced_in": "v0.10.0", "type": "module", "stability": 2, "stabilityText": "Stable", "desc": "
The node:util module supports the needs of Node.js internal APIs. Many of the\nutilities are useful for application and module developers as well. To access\nit:
\n
import util from 'node:util';\n\n
const util = require('node:util');\n", "methods": [ { "textRaw": "`util.callbackify(original)`", "name": "callbackify", "type": "method", "meta": { "added": [ "v8.2.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`original` {Function} An `async` function", "name": "original", "type": "Function", "desc": "An `async` function" } ], "return": { "textRaw": "Returns: {Function} a callback style function", "name": "return", "type": "Function", "desc": "a callback style function" } } ], "desc": "
Takes an async function (or a function that returns a Promise) and returns a\nfunction following the error-first callback style, i.e. taking\nan (err, value) => ... callback as the last argument. In the callback, the\nfirst argument will be the rejection reason (or null if the Promise\nresolved), and the second argument will be the resolved value.
\n
import { callbackify } from 'node:util';\n\nasync function fn() {\n return 'hello world';\n}\nconst callbackFunction = callbackify(fn);\n\ncallbackFunction((err, ret) => {\n if (err) throw err;\n console.log(ret);\n});\n\n
const { callbackify } = require('node:util');\n\nasync function fn() {\n return 'hello world';\n}\nconst callbackFunction = callbackify(fn);\n\ncallbackFunction((err, ret) => {\n if (err) throw err;\n console.log(ret);\n});\n\n
Will print:
\n
hello world\n\n
The callback is executed asynchronously, and will have a limited stack trace.\nIf the callback throws, the process will emit an 'uncaughtException'\nevent, and if not handled will exit.
\n
Since null has a special meaning as the first argument to a callback, if a\nwrapped function rejects a Promise with a falsy value as a reason, the value\nis wrapped in an Error with the original value stored in a field named\nreason.
\n
import util from 'node:util';\n\nfunction fn() {\n return Promise.reject(null);\n}\nconst callbackFunction = util.callbackify(fn);\n\ncallbackFunction((err, ret) => {\n // When the Promise was rejected with `null` it is wrapped with an Error and\n // the original value is stored in `reason`.\n err && Object.hasOwn(err, 'reason') && err.reason === null; // true\n});\n\n
const util = require('node:util');\n\nfunction fn() {\n return Promise.reject(null);\n}\nconst callbackFunction = util.callbackify(fn);\n\ncallbackFunction((err, ret) => {\n // When the Promise was rejected with `null` it is wrapped with an Error and\n // the original value is stored in `reason`.\n err && Object.hasOwn(err, 'reason') && err.reason === null; // true\n});\n" }, { "textRaw": "`util.convertProcessSignalToExitCode(signal)`", "name": "convertProcessSignalToExitCode", "type": "method", "meta": { "added": [ "v25.4.0", "v24.14.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`signal` {string} A signal name (e.g. `'SIGTERM'`)", "name": "signal", "type": "string", "desc": "A signal name (e.g. `'SIGTERM'`)" } ], "return": { "textRaw": "Returns: {number} The exit code corresponding to `signal`", "name": "return", "type": "number", "desc": "The exit code corresponding to `signal`" } } ], "desc": "
The util.convertProcessSignalToExitCode() method converts a signal name to its\ncorresponding POSIX exit code. Following the POSIX standard, the exit code\nfor a process terminated by a signal is calculated as 128 + signal number.
\n
If signal is not a valid signal name, then an error will be thrown. See\nsignal(7) for a list of valid signals.
\n
import { convertProcessSignalToExitCode } from 'node:util';\n\nconsole.log(convertProcessSignalToExitCode('SIGTERM')); // 143 (128 + 15)\nconsole.log(convertProcessSignalToExitCode('SIGKILL')); // 137 (128 + 9)\n\n
const { convertProcessSignalToExitCode } = require('node:util');\n\nconsole.log(convertProcessSignalToExitCode('SIGTERM')); // 143 (128 + 15)\nconsole.log(convertProcessSignalToExitCode('SIGKILL')); // 137 (128 + 9)\n\n
This is particularly useful when working with processes to determine\nthe exit code based on the signal that terminated the process.
" }, { "textRaw": "`util.debuglog(section[, callback])`", "name": "debuglog", "type": "method", "meta": { "added": [ "v0.11.3" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`section` {string} A string identifying the portion of the application for which the `debuglog` function is being created.", "name": "section", "type": "string", "desc": "A string identifying the portion of the application for which the `debuglog` function is being created." }, { "textRaw": "`callback` {Function} A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function.", "name": "callback", "type": "Function", "desc": "A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function.", "optional": true } ], "return": { "textRaw": "Returns: {Function} The logging function", "name": "return", "type": "Function", "desc": "The logging function" } } ], "desc": "
The util.debuglog() method is used to create a function that conditionally\nwrites debug messages to stderr based on the existence of the NODE_DEBUG\nenvironment variable. If the section name appears within the value of that\nenvironment variable, then the returned function operates similar to\nconsole.error(). If not, then the returned function is a no-op.
\n
import { debuglog } from 'node:util';\nconst log = debuglog('foo');\n\nlog('hello from foo [%d]', 123);\n\n
const { debuglog } = require('node:util');\nconst log = debuglog('foo');\n\nlog('hello from foo [%d]', 123);\n\n
If this program is run with NODE_DEBUG=foo in the environment, then\nit will output something like:
\n
FOO 3245: hello from foo [123]\n\n
where 3245 is the process id. If it is not run with that\nenvironment variable set, then it will not print anything.
\n
The section supports wildcard also:
\n
import { debuglog } from 'node:util';\nconst log = debuglog('foo-bar');\n\nlog('hi there, it\\'s foo-bar [%d]', 2333);\n\n
const { debuglog } = require('node:util');\nconst log = debuglog('foo-bar');\n\nlog('hi there, it\\'s foo-bar [%d]', 2333);\n\n
if it is run with NODE_DEBUG=foo* in the environment, then it will output\nsomething like:
\n
FOO-BAR 3257: hi there, it's foo-bar [2333]\n\n
Multiple comma-separated section names may be specified in the NODE_DEBUG\nenvironment variable: NODE_DEBUG=fs,net,tls.
\n
The optional callback argument can be used to replace the logging function\nwith a different function that doesn't have any initialization or\nunnecessary wrapping.
\n
import { debuglog } from 'node:util';\nlet log = debuglog('internals', (debug) => {\n // Replace with a logging function that optimizes out\n // testing if the section is enabled\n log = debug;\n});\n\n
const { debuglog } = require('node:util');\nlet log = debuglog('internals', (debug) => {\n // Replace with a logging function that optimizes out\n // testing if the section is enabled\n log = debug;\n});\n", "modules": [ { "textRaw": "`debuglog().enabled`", "name": "`debuglog().enabled`", "type": "module", "meta": { "added": [ "v14.9.0" ], "changes": [] }, "desc": "
<boolean>\n
The util.debuglog().enabled getter is used to create a test that can be used\nin conditionals based on the existence of the NODE_DEBUG environment variable.\nIf the section name appears within the value of that environment variable,\nthen the returned value will be true. If not, then the returned value will be\nfalse.
\n
import { debuglog } from 'node:util';\nconst enabled = debuglog('foo').enabled;\nif (enabled) {\n console.log('hello from foo [%d]', 123);\n}\n\n
const { debuglog } = require('node:util');\nconst enabled = debuglog('foo').enabled;\nif (enabled) {\n console.log('hello from foo [%d]', 123);\n}\n\n
If this program is run with NODE_DEBUG=foo in the environment, then it will\noutput something like:
\n
hello from foo [123]\n", "displayName": "`debuglog().enabled`" } ] }, { "textRaw": "`util.debug(section)`", "name": "debug", "type": "method", "meta": { "added": [ "v14.9.0" ], "changes": [] }, "signatures": [ { "params": [ { "name": "section" } ] } ], "desc": "
Alias for util.debuglog. Usage allows for readability of that doesn't imply\nlogging when only using util.debuglog().enabled.
" }, { "textRaw": "`util.deprecate(fn, msg[, code[, options]])`", "name": "deprecate", "type": "method", "meta": { "added": [ "v0.8.0" ], "changes": [ { "version": [ "v25.2.0", "v24.12.0" ], "pr-url": "https://github.com/nodejs/node/pull/59982", "description": "Add options object with modifyPrototype to conditionally modify the prototype of the deprecated object." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/16393", "description": "Deprecation warnings are only emitted once for each code." } ] }, "signatures": [ { "params": [ { "textRaw": "`fn` {Function} The function that is being deprecated.", "name": "fn", "type": "Function", "desc": "The function that is being deprecated." }, { "textRaw": "`msg` {string} A warning message to display when the deprecated function is invoked.", "name": "msg", "type": "string", "desc": "A warning message to display when the deprecated function is invoked." }, { "textRaw": "`code` {string} A deprecation code. See the list of deprecated APIs for a list of codes.", "name": "code", "type": "string", "desc": "A deprecation code. See the list of deprecated APIs for a list of codes.", "optional": true }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`modifyPrototype` {boolean} When false do not change the prototype of object while emitting the deprecation warning. **Default:** `true`.", "name": "modifyPrototype", "type": "boolean", "default": "`true`", "desc": "When false do not change the prototype of object while emitting the deprecation warning." } ], "optional": true } ], "return": { "textRaw": "Returns: {Function} The deprecated function wrapped to emit a warning.", "name": "return", "type": "Function", "desc": "The deprecated function wrapped to emit a warning." } } ], "desc": "
The util.deprecate() method wraps fn (which may be a function or class) in\nsuch a way that it is marked as deprecated.
\n
import { deprecate } from 'node:util';\n\nexport const obsoleteFunction = deprecate(() => {\n // Do something here.\n}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');\n\n
const { deprecate } = require('node:util');\n\nexports.obsoleteFunction = deprecate(() => {\n // Do something here.\n}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');\n\n
When called, util.deprecate() will return a function that will emit a\nDeprecationWarning using the 'warning' event. The warning will\nbe emitted and printed to stderr the first time the returned function is\ncalled. After the warning is emitted, the wrapped function is called without\nemitting a warning.
\n
If the same optional code is supplied in multiple calls to util.deprecate(),\nthe warning will be emitted only once for that code.
\n
import { deprecate } from 'node:util';\n\nconst fn1 = deprecate(\n () => 'a value',\n 'deprecation message',\n 'DEP0001',\n);\nconst fn2 = deprecate(\n () => 'a different value',\n 'other dep message',\n 'DEP0001',\n);\nfn1(); // Emits a deprecation warning with code DEP0001\nfn2(); // Does not emit a deprecation warning because it has the same code\n\n
const { deprecate } = require('node:util');\n\nconst fn1 = deprecate(\n function() {\n return 'a value';\n },\n 'deprecation message',\n 'DEP0001',\n);\nconst fn2 = deprecate(\n function() {\n return 'a different value';\n },\n 'other dep message',\n 'DEP0001',\n);\nfn1(); // Emits a deprecation warning with code DEP0001\nfn2(); // Does not emit a deprecation warning because it has the same code\n\n
If either the --no-deprecation or --no-warnings command-line flags are\nused, or if the process.noDeprecation property is set to true prior to\nthe first deprecation warning, the util.deprecate() method does nothing.
\n
If the --trace-deprecation or --trace-warnings command-line flags are set,\nor the process.traceDeprecation property is set to true, a warning and a\nstack trace are printed to stderr the first time the deprecated function is\ncalled.
\n
If the --throw-deprecation command-line flag is set, or the\nprocess.throwDeprecation property is set to true, then an exception will be\nthrown when the deprecated function is called.
\n
The --throw-deprecation command-line flag and process.throwDeprecation\nproperty take precedence over --trace-deprecation and\nprocess.traceDeprecation.
" }, { "textRaw": "`util.diff(actual, expected)`", "name": "diff", "type": "method", "meta": { "added": [ "v23.11.0", "v22.15.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "signatures": [ { "params": [ { "textRaw": "`actual` {Array|string} The first value to compare", "name": "actual", "type": "Array|string", "desc": "The first value to compare" }, { "textRaw": "`expected` {Array|string} The second value to compare", "name": "expected", "type": "Array|string", "desc": "The second value to compare" } ], "return": { "textRaw": "Returns: {Array} An array of difference entries. Each entry is an array with two elements:", "name": "return", "type": "Array", "desc": "An array of difference entries. Each entry is an array with two elements:", "options": [ { "textRaw": "`0` {number} Operation code: `-1` for delete, `0` for no-op/unchanged, `1` for insert", "name": "0", "type": "number", "desc": "Operation code: `-1` for delete, `0` for no-op/unchanged, `1` for insert" }, { "textRaw": "`1` {string} The value associated with the operation", "name": "1", "type": "string", "desc": "The value associated with the operation" } ] } } ], "desc": "
util.diff() compares two string or array values and returns an array of difference entries.\nIt uses the Myers diff algorithm to compute minimal differences, which is the same algorithm\nused internally by assertion error messages.
\n
If the values are equal, an empty array is returned.
\n
const { diff } = require('node:util');\n\n// Comparing strings\nconst actualString = '12345678';\nconst expectedString = '12!!5!7!';\nconsole.log(diff(actualString, expectedString));\n// [\n// [0, '1'],\n// [0, '2'],\n// [1, '3'],\n// [1, '4'],\n// [-1, '!'],\n// [-1, '!'],\n// [0, '5'],\n// [1, '6'],\n// [-1, '!'],\n// [0, '7'],\n// [1, '8'],\n// [-1, '!'],\n// ]\n// Comparing arrays\nconst actualArray = ['1', '2', '3'];\nconst expectedArray = ['1', '3', '4'];\nconsole.log(diff(actualArray, expectedArray));\n// [\n// [0, '1'],\n// [1, '2'],\n// [0, '3'],\n// [-1, '4'],\n// ]\n// Equal values return empty array\nconsole.log(diff('same', 'same'));\n// []\n" }, { "textRaw": "`util.format(format[, ...args])`", "name": "format", "type": "method", "meta": { "added": [ "v0.5.3" ], "changes": [ { "version": "v12.11.0", "pr-url": "https://github.com/nodejs/node/pull/29606", "description": "The `%c` specifier is ignored now." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/23162", "description": "The `format` argument is now only taken as such if it actually contains format specifiers." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/23162", "description": "If the `format` argument is not a format string, the output string's formatting is no longer dependent on the type of the first argument. This change removes previously present quotes from strings that were being output when the first argument was not a string." }, { "version": "v11.4.0", "pr-url": "https://github.com/nodejs/node/pull/23708", "description": "The `%d`, `%f`, and `%i` specifiers now support Symbols properly." }, { "version": "v11.4.0", "pr-url": "https://github.com/nodejs/node/pull/24806", "description": "The `%o` specifier's `depth` has default depth of 4 again." }, { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/17907", "description": "The `%o` specifier's `depth` option will now fall back to the default depth." }, { "version": "v10.12.0", "pr-url": "https://github.com/nodejs/node/pull/22097", "description": "The `%d` and `%i` specifiers now support BigInt." }, { "version": "v8.4.0", "pr-url": "https://github.com/nodejs/node/pull/14558", "description": "The `%o` and `%O` specifiers are supported now." } ] }, "signatures": [ { "params": [ { "textRaw": "`format` {string} A `printf`-like format string.", "name": "format", "type": "string", "desc": "A `printf`-like format string." }, { "name": "...args", "optional": true } ] } ], "desc": "
The util.format() method returns a formatted string using the first argument\nas a printf-like format string which can contain zero or more format\nspecifiers. Each specifier is replaced with the converted value from the\ncorresponding argument. Supported specifiers are:
\n
%s: String will be used to convert all values except BigInt, Object\nand -0. BigInt values will be represented with an n and Objects that\nhave neither a user defined toString function nor Symbol.toPrimitive function are inspected using util.inspect()\nwith options { depth: 0, colors: false, compact: 3 }.%d: Number will be used to convert all values except BigInt and\nSymbol.%i: parseInt(value, 10) is used for all values except BigInt and\nSymbol.%f: parseFloat(value) is used for all values expect Symbol.%j: JSON. Replaced with the string '[Circular]' if the argument contains\ncircular references.%o: Object. A string representation of an object with generic JavaScript\nobject formatting. Similar to util.inspect() with options\n{ showHidden: true, showProxy: true }. This will show the full object\nincluding non-enumerable properties and proxies.%O: Object. A string representation of an object with generic JavaScript\nobject formatting. Similar to util.inspect() without options. This will show\nthe full object not including non-enumerable properties and proxies.%c: CSS. This specifier is ignored and will skip any CSS passed in.%%: single percent sign ('%'). This does not consume an argument.<string> The formatted string\n
If a specifier does not have a corresponding argument, it is not replaced:
\n
util.format('%s:%s', 'foo');\n// Returns: 'foo:%s'\n\n
Values that are not part of the format string are formatted using\nutil.inspect() if their type is not string.
\n
If there are more arguments passed to the util.format() method than the\nnumber of specifiers, the extra arguments are concatenated to the returned\nstring, separated by spaces:
\n
util.format('%s:%s', 'foo', 'bar', 'baz');\n// Returns: 'foo:bar baz'\n\n
If the first argument does not contain a valid format specifier, util.format()\nreturns a string that is the concatenation of all arguments separated by spaces:
\n
util.format(1, 2, 3);\n// Returns: '1 2 3'\n\n
If only one argument is passed to util.format(), it is returned as it is\nwithout any formatting:
\n
util.format('%% %s');\n// Returns: '%% %s'\n\n
util.format() is a synchronous method that is intended as a debugging tool.\nSome input values can have a significant performance overhead that can block the\nevent loop. Use this function with care and never in a hot code path.
" }, { "textRaw": "`util.formatWithOptions(inspectOptions, format[, ...args])`", "name": "formatWithOptions", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`inspectOptions` {Object}", "name": "inspectOptions", "type": "Object" }, { "textRaw": "`format` {string}", "name": "format", "type": "string" }, { "name": "...args", "optional": true } ] } ], "desc": "
This function is identical to util.format(), except in that it takes\nan inspectOptions argument which specifies options that are passed along to\nutil.inspect().
\n
util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 });\n// Returns 'See object { foo: 42 }', where `42` is colored as a number\n// when printed to a terminal.\n" }, { "textRaw": "`util.getCallSites([frameCount][, options])`", "name": "getCallSites", "type": "method", "meta": { "added": [ "v22.9.0" ], "changes": [ { "version": [ "v23.7.0", "v22.14.0" ], "pr-url": "https://github.com/nodejs/node/pull/56584", "description": "Property `column` is deprecated in favor of `columnNumber`." }, { "version": [ "v23.7.0", "v22.14.0" ], "pr-url": "https://github.com/nodejs/node/pull/56551", "description": "Property `CallSite.scriptId` is exposed." }, { "version": [ "v23.3.0", "v22.12.0" ], "pr-url": "https://github.com/nodejs/node/pull/55626", "description": "The API is renamed from `util.getCallSite` to `util.getCallSites()`." } ] }, "stability": 1.1, "stabilityText": "Active development", "signatures": [ { "params": [ { "textRaw": "`frameCount` {integer} Optional number of frames to capture as call site objects. **Default:** `10`. Allowable range is between 1 and 200.", "name": "frameCount", "type": "integer", "default": "`10`. Allowable range is between 1 and 200", "desc": "Optional number of frames to capture as call site objects.", "optional": true }, { "textRaw": "`options` {Object} Optional", "name": "options", "type": "Object", "desc": "Optional", "options": [ { "textRaw": "`sourceMap` {boolean} Reconstruct the original location in the stacktrace from the source-map. Enabled by default with the flag `--enable-source-maps`.", "name": "sourceMap", "type": "boolean", "desc": "Reconstruct the original location in the stacktrace from the source-map. Enabled by default with the flag `--enable-source-maps`." } ], "optional": true } ], "return": { "textRaw": "Returns: {Object[]} An array of call site objects", "name": "return", "type": "Object[]", "desc": "An array of call site objects", "options": [ { "textRaw": "`functionName` {string} Returns the name of the function associated with this call site.", "name": "functionName", "type": "string", "desc": "Returns the name of the function associated with this call site." }, { "textRaw": "`scriptName` {string} Returns the name of the resource that contains the script for the function for this call site.", "name": "scriptName", "type": "string", "desc": "Returns the name of the resource that contains the script for the function for this call site." }, { "textRaw": "`scriptId` {string} Returns the unique id of the script, as in Chrome DevTools protocol `Runtime.ScriptId`.", "name": "scriptId", "type": "string", "desc": "Returns the unique id of the script, as in Chrome DevTools protocol `Runtime.ScriptId`." }, { "textRaw": "`lineNumber` {number} Returns the JavaScript script line number (1-based).", "name": "lineNumber", "type": "number", "desc": "Returns the JavaScript script line number (1-based)." }, { "textRaw": "`columnNumber` {number} Returns the JavaScript script column number (1-based).", "name": "columnNumber", "type": "number", "desc": "Returns the JavaScript script column number (1-based)." } ] } } ], "desc": "
Returns an array of call site objects containing the stack of\nthe caller function.
\n
Unlike accessing an error.stack, the result returned from this API is not\ninterfered with Error.prepareStackTrace.
\n
import { getCallSites } from 'node:util';\n\nfunction exampleFunction() {\n const callSites = getCallSites();\n\n console.log('Call Sites:');\n callSites.forEach((callSite, index) => {\n console.log(`CallSite ${index + 1}:`);\n console.log(`Function Name: ${callSite.functionName}`);\n console.log(`Script Name: ${callSite.scriptName}`);\n console.log(`Line Number: ${callSite.lineNumber}`);\n console.log(`Column Number: ${callSite.columnNumber}`);\n });\n // CallSite 1:\n // Function Name: exampleFunction\n // Script Name: /home/example.js\n // Line Number: 5\n // Column Number: 26\n\n // CallSite 2:\n // Function Name: anotherFunction\n // Script Name: /home/example.js\n // Line Number: 22\n // Column Number: 3\n\n // ...\n}\n\n// A function to simulate another stack layer\nfunction anotherFunction() {\n exampleFunction();\n}\n\nanotherFunction();\n\n
const { getCallSites } = require('node:util');\n\nfunction exampleFunction() {\n const callSites = getCallSites();\n\n console.log('Call Sites:');\n callSites.forEach((callSite, index) => {\n console.log(`CallSite ${index + 1}:`);\n console.log(`Function Name: ${callSite.functionName}`);\n console.log(`Script Name: ${callSite.scriptName}`);\n console.log(`Line Number: ${callSite.lineNumber}`);\n console.log(`Column Number: ${callSite.columnNumber}`);\n });\n // CallSite 1:\n // Function Name: exampleFunction\n // Script Name: /home/example.js\n // Line Number: 5\n // Column Number: 26\n\n // CallSite 2:\n // Function Name: anotherFunction\n // Script Name: /home/example.js\n // Line Number: 22\n // Column Number: 3\n\n // ...\n}\n\n// A function to simulate another stack layer\nfunction anotherFunction() {\n exampleFunction();\n}\n\nanotherFunction();\n\n
It is possible to reconstruct the original locations by setting the option sourceMap to true.\nIf the source map is not available, the original location will be the same as the current location.\nWhen the --enable-source-maps flag is enabled,sourceMap will be true by default.
\n
import { getCallSites } from 'node:util';\n\ninterface Foo {\n foo: string;\n}\n\nconst callSites = getCallSites({ sourceMap: true });\n\n// With sourceMap:\n// Function Name: ''\n// Script Name: example.js\n// Line Number: 7\n// Column Number: 26\n\n// Without sourceMap:\n// Function Name: ''\n// Script Name: example.js\n// Line Number: 2\n// Column Number: 26\n\n
const { getCallSites } = require('node:util');\n\nconst callSites = getCallSites({ sourceMap: true });\n\n// With sourceMap:\n// Function Name: ''\n// Script Name: example.js\n// Line Number: 7\n// Column Number: 26\n\n// Without sourceMap:\n// Function Name: ''\n// Script Name: example.js\n// Line Number: 2\n// Column Number: 26\n" }, { "textRaw": "`util.getSystemErrorName(err)`", "name": "getSystemErrorName", "type": "method", "meta": { "added": [ "v9.7.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`err` {number}", "name": "err", "type": "number" } ], "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" } } ], "desc": "
Returns the string name for a numeric error code that comes from a Node.js API.\nThe mapping between error codes and error names is platform-dependent.\nSee Common System Errors for the names of common errors.
\n
fs.access('file/that/does/not/exist', (err) => {\n const name = util.getSystemErrorName(err.errno);\n console.error(name); // ENOENT\n});\n" }, { "textRaw": "`util.getSystemErrorMap()`", "name": "getSystemErrorMap", "type": "method", "meta": { "added": [ "v16.0.0", "v14.17.0" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {Map}", "name": "return", "type": "Map" } } ], "desc": "
Returns a Map of all system error codes available from the Node.js API.\nThe mapping between error codes and error names is platform-dependent.\nSee Common System Errors for the names of common errors.
\n
fs.access('file/that/does/not/exist', (err) => {\n const errorMap = util.getSystemErrorMap();\n const name = errorMap.get(err.errno);\n console.error(name); // ENOENT\n});\n" }, { "textRaw": "`util.getSystemErrorMessage(err)`", "name": "getSystemErrorMessage", "type": "method", "meta": { "added": [ "v23.1.0", "v22.12.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`err` {number}", "name": "err", "type": "number" } ], "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" } } ], "desc": "
Returns the string message for a numeric error code that comes from a Node.js\nAPI.\nThe mapping between error codes and string messages is platform-dependent.
\n
fs.access('file/that/does/not/exist', (err) => {\n const message = util.getSystemErrorMessage(err.errno);\n console.error(message); // No such file or directory\n});\n" }, { "textRaw": "`util.setTraceSigInt(enable)`", "name": "setTraceSigInt", "type": "method", "meta": { "added": [ "v24.6.0", "v22.19.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`enable` {boolean}", "name": "enable", "type": "boolean" } ] } ], "desc": "
Enable or disable printing a stack trace on SIGINT. The API is only available on the main thread.
" }, { "textRaw": "`util.inherits(constructor, superConstructor)`", "name": "inherits", "type": "method", "meta": { "added": [ "v0.3.0" ], "changes": [ { "version": "v5.0.0", "pr-url": "https://github.com/nodejs/node/pull/3455", "description": "The `constructor` parameter can refer to an ES6 class now." } ] }, "stability": 3, "stabilityText": "Legacy: Use ES2015 class syntax and `extends` keyword instead.", "signatures": [ { "params": [ { "textRaw": "`constructor` {Function}", "name": "constructor", "type": "Function" }, { "textRaw": "`superConstructor` {Function}", "name": "superConstructor", "type": "Function" } ] } ], "desc": "
Usage of util.inherits() is discouraged. Please use the ES6 class and\nextends keywords to get language level inheritance support. Also note\nthat the two styles are semantically incompatible.
\n
Inherit the prototype methods from one constructor into another. The\nprototype of constructor will be set to a new object created from\nsuperConstructor.
\n
This mainly adds some input validation on top of\nObject.setPrototypeOf(constructor.prototype, superConstructor.prototype).\nAs an additional convenience, superConstructor will be accessible\nthrough the constructor.super_ property.
\n
const util = require('node:util');\nconst EventEmitter = require('node:events');\n\nfunction MyStream() {\n EventEmitter.call(this);\n}\n\nutil.inherits(MyStream, EventEmitter);\n\nMyStream.prototype.write = function(data) {\n this.emit('data', data);\n};\n\nconst stream = new MyStream();\n\nconsole.log(stream instanceof EventEmitter); // true\nconsole.log(MyStream.super_ === EventEmitter); // true\n\nstream.on('data', (data) => {\n console.log(`Received data: \"${data}\"`);\n});\nstream.write('It works!'); // Received data: \"It works!\"\n\n
ES6 example using class and extends:
\n
import EventEmitter from 'node:events';\n\nclass MyStream extends EventEmitter {\n write(data) {\n this.emit('data', data);\n }\n}\n\nconst stream = new MyStream();\n\nstream.on('data', (data) => {\n console.log(`Received data: \"${data}\"`);\n});\nstream.write('With ES6');\n\n
const EventEmitter = require('node:events');\n\nclass MyStream extends EventEmitter {\n write(data) {\n this.emit('data', data);\n }\n}\n\nconst stream = new MyStream();\n\nstream.on('data', (data) => {\n console.log(`Received data: \"${data}\"`);\n});\nstream.write('With ES6');\n" }, { "textRaw": "`util.inspect(object[, options])`", "name": "inspect", "type": "method", "signatures": [ { "params": [ { "name": "object" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "`util.inspect(object[, showHidden[, depth[, colors]]])`", "name": "inspect", "type": "method", "meta": { "added": [ "v0.3.0" ], "changes": [ { "version": [ "v25.0.0" ], "pr-url": "https://github.com/nodejs/node/pull/59710", "description": "The util.inspect.styles.regexp style is now a method that is invoked for coloring the stringified regular expression." }, { "version": [ "v17.3.0", "v16.14.0" ], "pr-url": "https://github.com/nodejs/node/pull/41003", "description": "The `numericSeparator` option is supported now." }, { "version": "v16.18.0", "pr-url": "https://github.com/nodejs/node/pull/43576", "description": "add support for `maxArrayLength` when inspecting `Set` and `Map`." }, { "version": [ "v14.6.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/33690", "description": "If `object` is from a different `vm.Context` now, a custom inspection function on it will not receive context-specific arguments anymore." }, { "version": [ "v13.13.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/32392", "description": "The `maxStringLength` option is supported now." }, { "version": [ "v13.5.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/30768", "description": "User defined prototype properties are inspected in case `showHidden` is `true`." }, { "version": "v13.0.0", "pr-url": "https://github.com/nodejs/node/pull/27685", "description": "Circular references now include a marker to the reference." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/27109", "description": "The `compact` options default is changed to `3` and the `breakLength` options default is changed to `80`." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/24971", "description": "Internal properties no longer appear in the context argument of a custom inspection function." }, { "version": "v11.11.0", "pr-url": "https://github.com/nodejs/node/pull/26269", "description": "The `compact` option accepts numbers for a new output mode." }, { "version": "v11.7.0", "pr-url": "https://github.com/nodejs/node/pull/25006", "description": "ArrayBuffers now also show their binary contents." }, { "version": "v11.5.0", "pr-url": "https://github.com/nodejs/node/pull/24852", "description": "The `getters` option is supported now." }, { "version": "v11.4.0", "pr-url": "https://github.com/nodejs/node/pull/24326", "description": "The `depth` default changed back to `2`." }, { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/22846", "description": "The `depth` default changed to `20`." }, { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/22756", "description": "The inspection output is now limited to about 128 MiB. Data above that size will not be fully inspected." }, { "version": "v10.12.0", "pr-url": "https://github.com/nodejs/node/pull/22788", "description": "The `sorted` option is supported now." }, { "version": "v10.6.0", "pr-url": "https://github.com/nodejs/node/pull/20725", "description": "Inspecting linked lists and similar objects is now possible up to the maximum call stack size." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19259", "description": "The `WeakMap` and `WeakSet` entries can now be inspected as well." }, { "version": "v9.9.0", "pr-url": "https://github.com/nodejs/node/pull/17576", "description": "The `compact` option is supported now." }, { "version": "v6.6.0", "pr-url": "https://github.com/nodejs/node/pull/8174", "description": "Custom inspection functions can now return `this`." }, { "version": "v6.3.0", "pr-url": "https://github.com/nodejs/node/pull/7499", "description": "The `breakLength` option is supported now." }, { "version": "v6.1.0", "pr-url": "https://github.com/nodejs/node/pull/6334", "description": "The `maxArrayLength` option is supported now; in particular, long arrays are truncated by default." }, { "version": "v6.1.0", "pr-url": "https://github.com/nodejs/node/pull/6465", "description": "The `showProxy` option is supported now." } ] }, "signatures": [ { "params": [ { "textRaw": "`object` {any} Any JavaScript primitive or `Object`.", "name": "object", "type": "any", "desc": "Any JavaScript primitive or `Object`." }, { "textRaw": "`showHidden` {boolean} If `true`, `object`'s non-enumerable symbols and properties are included in the formatted result. {WeakMap} and {WeakSet} entries are also included as well as user defined prototype properties (excluding method properties). **Default:** `false`.", "name": "showHidden", "type": "boolean", "default": "`false`", "desc": "If `true`, `object`'s non-enumerable symbols and properties are included in the formatted result. {WeakMap} and {WeakSet} entries are also included as well as user defined prototype properties (excluding method properties).", "optional": true }, { "textRaw": "`depth` {number} Specifies the number of times to recurse while formatting `object`. This is useful for inspecting large objects. To recurse up to the maximum call stack size pass `Infinity` or `null`. **Default:** `2`.", "name": "depth", "type": "number", "default": "`2`", "desc": "Specifies the number of times to recurse while formatting `object`. This is useful for inspecting large objects. To recurse up to the maximum call stack size pass `Infinity` or `null`.", "optional": true }, { "textRaw": "`colors` {boolean} If `true`, the output is styled with ANSI color codes. Colors are customizable. See Customizing `util.inspect` colors. **Default:** `false`.", "name": "colors", "type": "boolean", "default": "`false`", "desc": "If `true`, the output is styled with ANSI color codes. Colors are customizable. See Customizing `util.inspect` colors.", "optional": true } ], "return": { "textRaw": "Returns: {string} The representation of `object`.", "name": "return", "type": "string", "desc": "The representation of `object`." } } ], "desc": "
The util.inspect() method returns a string representation of object that is\nintended for debugging. The output of util.inspect may change at any time\nand should not be depended upon programmatically. Additional options may be\npassed that alter the result.\nutil.inspect() will use the constructor's name and/or Symbol.toStringTag\nproperty to make an identifiable tag for an inspected value.
\n
class Foo {\n get [Symbol.toStringTag]() {\n return 'bar';\n }\n}\n\nclass Bar {}\n\nconst baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });\n\nutil.inspect(new Foo()); // 'Foo [bar] {}'\nutil.inspect(new Bar()); // 'Bar {}'\nutil.inspect(baz); // '[foo] {}'\n\n
Circular references point to their anchor by using a reference index:
\n
import { inspect } from 'node:util';\n\nconst obj = {};\nobj.a = [obj];\nobj.b = {};\nobj.b.inner = obj.b;\nobj.b.obj = obj;\n\nconsole.log(inspect(obj));\n// <ref *1> {\n// a: [ [Circular *1] ],\n// b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }\n// }\n\n
const { inspect } = require('node:util');\n\nconst obj = {};\nobj.a = [obj];\nobj.b = {};\nobj.b.inner = obj.b;\nobj.b.obj = obj;\n\nconsole.log(inspect(obj));\n// <ref *1> {\n// a: [ [Circular *1] ],\n// b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }\n// }\n\n
The following example inspects all properties of the util object:
\n
import util from 'node:util';\n\nconsole.log(util.inspect(util, { showHidden: true, depth: null }));\n\n
const util = require('node:util');\n\nconsole.log(util.inspect(util, { showHidden: true, depth: null }));\n\n
The following example highlights the effect of the compact option:
\n
import { inspect } from 'node:util';\n\nconst o = {\n a: [1, 2, [[\n 'Lorem ipsum dolor sit amet,\\nconsectetur adipiscing elit, sed do ' +\n 'eiusmod \\ntempor incididunt ut labore et dolore magna aliqua.',\n 'test',\n 'foo']], 4],\n b: new Map([['za', 1], ['zb', 'test']]),\n};\nconsole.log(inspect(o, { compact: true, depth: 5, breakLength: 80 }));\n\n// { a:\n// [ 1,\n// 2,\n// [ [ 'Lorem ipsum dolor sit amet,\\nconsectetur [...]', // A long line\n// 'test',\n// 'foo' ] ],\n// 4 ],\n// b: Map(2) { 'za' => 1, 'zb' => 'test' } }\n\n// Setting `compact` to false or an integer creates more reader friendly output.\nconsole.log(inspect(o, { compact: false, depth: 5, breakLength: 80 }));\n\n// {\n// a: [\n// 1,\n// 2,\n// [\n// [\n// 'Lorem ipsum dolor sit amet,\\n' +\n// 'consectetur adipiscing elit, sed do eiusmod \\n' +\n// 'tempor incididunt ut labore et dolore magna aliqua.',\n// 'test',\n// 'foo'\n// ]\n// ],\n// 4\n// ],\n// b: Map(2) {\n// 'za' => 1,\n// 'zb' => 'test'\n// }\n// }\n\n// Setting `breakLength` to e.g. 150 will print the \"Lorem ipsum\" text in a\n// single line.\n\n
const { inspect } = require('node:util');\n\nconst o = {\n a: [1, 2, [[\n 'Lorem ipsum dolor sit amet,\\nconsectetur adipiscing elit, sed do ' +\n 'eiusmod \\ntempor incididunt ut labore et dolore magna aliqua.',\n 'test',\n 'foo']], 4],\n b: new Map([['za', 1], ['zb', 'test']]),\n};\nconsole.log(inspect(o, { compact: true, depth: 5, breakLength: 80 }));\n\n// { a:\n// [ 1,\n// 2,\n// [ [ 'Lorem ipsum dolor sit amet,\\nconsectetur [...]', // A long line\n// 'test',\n// 'foo' ] ],\n// 4 ],\n// b: Map(2) { 'za' => 1, 'zb' => 'test' } }\n\n// Setting `compact` to false or an integer creates more reader friendly output.\nconsole.log(inspect(o, { compact: false, depth: 5, breakLength: 80 }));\n\n// {\n// a: [\n// 1,\n// 2,\n// [\n// [\n// 'Lorem ipsum dolor sit amet,\\n' +\n// 'consectetur adipiscing elit, sed do eiusmod \\n' +\n// 'tempor incididunt ut labore et dolore magna aliqua.',\n// 'test',\n// 'foo'\n// ]\n// ],\n// 4\n// ],\n// b: Map(2) {\n// 'za' => 1,\n// 'zb' => 'test'\n// }\n// }\n\n// Setting `breakLength` to e.g. 150 will print the \"Lorem ipsum\" text in a\n// single line.\n\n
The showHidden option allows <WeakMap> and <WeakSet> entries to be\ninspected. If there are more entries than maxArrayLength, there is no\nguarantee which entries are displayed. That means retrieving the same\n<WeakSet> entries twice may result in different output. Furthermore, entries\nwith no remaining strong references may be garbage collected at any time.
\n
import { inspect } from 'node:util';\n\nconst obj = { a: 1 };\nconst obj2 = { b: 2 };\nconst weakSet = new WeakSet([obj, obj2]);\n\nconsole.log(inspect(weakSet, { showHidden: true }));\n// WeakSet { { a: 1 }, { b: 2 } }\n\n
const { inspect } = require('node:util');\n\nconst obj = { a: 1 };\nconst obj2 = { b: 2 };\nconst weakSet = new WeakSet([obj, obj2]);\n\nconsole.log(inspect(weakSet, { showHidden: true }));\n// WeakSet { { a: 1 }, { b: 2 } }\n\n
The sorted option ensures that an object's property insertion order does not\nimpact the result of util.inspect().
\n
import { inspect } from 'node:util';\nimport assert from 'node:assert';\n\nconst o1 = {\n b: [2, 3, 1],\n a: '`a` comes before `b`',\n c: new Set([2, 3, 1]),\n};\nconsole.log(inspect(o1, { sorted: true }));\n// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } }\nconsole.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));\n// { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }\n\nconst o2 = {\n c: new Set([2, 1, 3]),\n a: '`a` comes before `b`',\n b: [2, 3, 1],\n};\nassert.strict.equal(\n inspect(o1, { sorted: true }),\n inspect(o2, { sorted: true }),\n);\n\n
const { inspect } = require('node:util');\nconst assert = require('node:assert');\n\nconst o1 = {\n b: [2, 3, 1],\n a: '`a` comes before `b`',\n c: new Set([2, 3, 1]),\n};\nconsole.log(inspect(o1, { sorted: true }));\n// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } }\nconsole.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));\n// { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }\n\nconst o2 = {\n c: new Set([2, 1, 3]),\n a: '`a` comes before `b`',\n b: [2, 3, 1],\n};\nassert.strict.equal(\n inspect(o1, { sorted: true }),\n inspect(o2, { sorted: true }),\n);\n\n
The numericSeparator option adds an underscore every three digits to all\nnumbers.
\n
import { inspect } from 'node:util';\n\nconst thousand = 1000;\nconst million = 1000000;\nconst bigNumber = 123456789n;\nconst bigDecimal = 1234.12345;\n\nconsole.log(inspect(thousand, { numericSeparator: true }));\n// 1_000\nconsole.log(inspect(million, { numericSeparator: true }));\n// 1_000_000\nconsole.log(inspect(bigNumber, { numericSeparator: true }));\n// 123_456_789n\nconsole.log(inspect(bigDecimal, { numericSeparator: true }));\n// 1_234.123_45\n\n
const { inspect } = require('node:util');\n\nconst thousand = 1000;\nconst million = 1000000;\nconst bigNumber = 123456789n;\nconst bigDecimal = 1234.12345;\n\nconsole.log(inspect(thousand, { numericSeparator: true }));\n// 1_000\nconsole.log(inspect(million, { numericSeparator: true }));\n// 1_000_000\nconsole.log(inspect(bigNumber, { numericSeparator: true }));\n// 123_456_789n\nconsole.log(inspect(bigDecimal, { numericSeparator: true }));\n// 1_234.123_45\n\n
util.inspect() is a synchronous method intended for debugging. Its maximum\noutput length is approximately 128 MiB. Inputs that result in longer output will\nbe truncated.
", "miscs": [ { "textRaw": "Customizing `util.inspect` colors", "name": "Customizing `util.inspect` colors", "type": "misc", "desc": "
Color output (if enabled) of util.inspect is customizable globally\nvia the util.inspect.styles and util.inspect.colors properties.
\n
util.inspect.styles is a map associating a style name to a color from\nutil.inspect.colors.
\n
The default styles and associated colors are:
\n
bigint: yellowboolean: yellowdate: magentamodule: underlinename: (no styling)null: boldnumber: yellowregexp: A method that colors character classes, groups, assertions, and\nother parts for improved readability. To customize the coloring, change the\ncolors property. It is set to\n['red', 'green', 'yellow', 'cyan', 'magenta'] by default and may be\nadjusted as needed. The array is repetitively iterated through depending on\nthe \"depth\".special: cyan (e.g., Proxies)string: greensymbol: greenundefined: grey\n
Color styling uses ANSI control codes that may not be supported on all\nterminals. To verify color support use tty.hasColors().
\n
Predefined control codes are listed below (grouped as \"Modifiers\", \"Foreground\ncolors\", and \"Background colors\").
", "miscs": [ { "textRaw": "Complex custom coloring", "name": "complex_custom_coloring", "type": "misc", "desc": "
It is possible to define a method as style. It receives the stringified value\nof the input. It is invoked in case coloring is active and the type is\ninspected.
\n
Example: util.inspect.styles.regexp(value)
\n
value <string> The string representation of the input type.<string> The adjusted representation of object.", "displayName": "Complex custom coloring" }, { "textRaw": "Modifiers", "name": "modifiers", "type": "misc", "desc": "
Modifier support varies throughout different terminals. They will mostly be\nignored, if not supported.
\n
reset - Resets all (color) modifiers to their defaultsstrikeThrough, crossedout, crossedOut)hidden - Prints the text, but makes it invisible (Alias: conceal)faint)swapcolors, swapColors)doubleUnderline)", "displayName": "Modifiers" }, { "textRaw": "Foreground colors", "name": "foreground_colors", "type": "misc", "desc": "
blackredgreenyellowbluemagentacyanwhitegray (alias: grey, blackBright)redBrightgreenBrightyellowBrightblueBrightmagentaBrightcyanBrightwhiteBright", "displayName": "Foreground colors" }, { "textRaw": "Background colors", "name": "background_colors", "type": "misc", "desc": "
bgBlackbgRedbgGreenbgYellowbgBluebgMagentabgCyanbgWhitebgGray (alias: bgGrey, bgBlackBright)bgRedBrightbgGreenBrightbgYellowBrightbgBlueBrightbgMagentaBrightbgCyanBrightbgWhiteBright", "displayName": "Background colors" } ] }, { "textRaw": "Custom inspection functions on objects", "name": "Custom inspection functions on objects", "type": "misc", "meta": { "added": [ "v0.1.97" ], "changes": [ { "version": [ "v17.3.0", "v16.14.0" ], "pr-url": "https://github.com/nodejs/node/pull/41019", "description": "The inspect argument is added for more interoperability." } ] }, "desc": "
Objects may also define their own\n[util.inspect.custom](depth, opts, inspect) function,\nwhich util.inspect() will invoke and use the result of when inspecting\nthe object.
\n
import { inspect } from 'node:util';\n\nclass Box {\n constructor(value) {\n this.value = value;\n }\n\n [inspect.custom](depth, options, inspect) {\n if (depth < 0) {\n return options.stylize('[Box]', 'special');\n }\n\n const newOptions = Object.assign({}, options, {\n depth: options.depth === null ? null : options.depth - 1,\n });\n\n // Five space padding because that's the size of \"Box< \".\n const padding = ' '.repeat(5);\n const inner = inspect(this.value, newOptions)\n .replace(/\\n/g, `\\n${padding}`);\n return `${options.stylize('Box', 'special')}< ${inner} >`;\n }\n}\n\nconst box = new Box(true);\n\nconsole.log(inspect(box));\n// \"Box< true >\"\n\n
const { inspect } = require('node:util');\n\nclass Box {\n constructor(value) {\n this.value = value;\n }\n\n [inspect.custom](depth, options, inspect) {\n if (depth < 0) {\n return options.stylize('[Box]', 'special');\n }\n\n const newOptions = Object.assign({}, options, {\n depth: options.depth === null ? null : options.depth - 1,\n });\n\n // Five space padding because that's the size of \"Box< \".\n const padding = ' '.repeat(5);\n const inner = inspect(this.value, newOptions)\n .replace(/\\n/g, `\\n${padding}`);\n return `${options.stylize('Box', 'special')}< ${inner} >`;\n }\n}\n\nconst box = new Box(true);\n\nconsole.log(inspect(box));\n// \"Box< true >\"\n\n
Custom [util.inspect.custom](depth, opts, inspect) functions typically return\na string but may return a value of any type that will be formatted accordingly\nby util.inspect().
\n
import { inspect } from 'node:util';\n\nconst obj = { foo: 'this will not show up in the inspect() output' };\nobj[inspect.custom] = (depth) => {\n return { bar: 'baz' };\n};\n\nconsole.log(inspect(obj));\n// \"{ bar: 'baz' }\"\n\n
const { inspect } = require('node:util');\n\nconst obj = { foo: 'this will not show up in the inspect() output' };\nobj[inspect.custom] = (depth) => {\n return { bar: 'baz' };\n};\n\nconsole.log(inspect(obj));\n// \"{ bar: 'baz' }\"\n" } ], "properties": [ { "textRaw": "Type: {symbol} that can be used to declare custom inspect functions.", "name": "custom", "type": "symbol", "meta": { "added": [ "v6.6.0" ], "changes": [ { "version": "v10.12.0", "pr-url": "https://github.com/nodejs/node/pull/20857", "description": "This is now defined as a shared symbol." } ] }, "desc": "
In addition to being accessible through util.inspect.custom, this\nsymbol is registered globally and can be\naccessed in any environment as Symbol.for('nodejs.util.inspect.custom').
\n
Using this allows code to be written in a portable fashion, so that the custom\ninspect function is used in an Node.js environment and ignored in the browser.\nThe util.inspect() function itself is passed as third argument to the custom\ninspect function to allow further portability.
\n
const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom');\n\nclass Password {\n constructor(value) {\n this.value = value;\n }\n\n toString() {\n return 'xxxxxxxx';\n }\n\n [customInspectSymbol](depth, inspectOptions, inspect) {\n return `Password <${this.toString()}>`;\n }\n}\n\nconst password = new Password('r0sebud');\nconsole.log(password);\n// Prints Password <xxxxxxxx>\n\n
See Custom inspection functions on Objects for more details.
", "shortDesc": "that can be used to declare custom inspect functions." }, { "textRaw": "`util.inspect.defaultOptions`", "name": "defaultOptions", "type": "property", "meta": { "added": [ "v6.4.0" ], "changes": [] }, "desc": "
The defaultOptions value allows customization of the default options used by\nutil.inspect. This is useful for functions like console.log or\nutil.format which implicitly call into util.inspect. It shall be set to an\nobject containing one or more valid util.inspect() options. Setting\noption properties directly is also supported.
\n
import { inspect } from 'node:util';\nconst arr = Array(156).fill(0);\n\nconsole.log(arr); // Logs the truncated array\ninspect.defaultOptions.maxArrayLength = null;\nconsole.log(arr); // logs the full array\n\n
const { inspect } = require('node:util');\nconst arr = Array(156).fill(0);\n\nconsole.log(arr); // Logs the truncated array\ninspect.defaultOptions.maxArrayLength = null;\nconsole.log(arr); // logs the full array\n" } ] }, { "textRaw": "`util.isDeepStrictEqual(val1, val2[, options])`", "name": "isDeepStrictEqual", "type": "method", "meta": { "added": [ "v9.0.0" ], "changes": [ { "version": "v24.9.0", "pr-url": "https://github.com/nodejs/node/pull/59762", "description": "Added `options` parameter to allow skipping prototype comparison." } ] }, "signatures": [ { "params": [ { "textRaw": "`val1` {any}", "name": "val1", "type": "any" }, { "textRaw": "`val2` {any}", "name": "val2", "type": "any" }, { "name": "options", "optional": true } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if there is deep strict equality between val1 and val2.\nOtherwise, returns false.
\n
By default, deep strict equality includes comparison of object prototypes and\nconstructors. When skipPrototype is true, objects with\ndifferent prototypes or constructors can still be considered equal if their\nenumerable properties are deeply strictly equal.
\n
const util = require('node:util');\n\nclass Foo {\n constructor(a) {\n this.a = a;\n }\n}\n\nclass Bar {\n constructor(a) {\n this.a = a;\n }\n}\n\nconst foo = new Foo(1);\nconst bar = new Bar(1);\n\n// Different constructors, same properties\nconsole.log(util.isDeepStrictEqual(foo, bar));\n// false\n\nconsole.log(util.isDeepStrictEqual(foo, bar, true));\n// true\n\n
See assert.deepStrictEqual() for more information about deep strict\nequality.
" }, { "textRaw": "`util.parseArgs([config])`", "name": "parseArgs", "type": "method", "meta": { "added": [ "v18.3.0", "v16.17.0" ], "changes": [ { "version": [ "v22.4.0", "v20.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/53107", "description": "add support for allowing negative options in input `config`." }, { "version": [ "v20.0.0" ], "pr-url": "https://github.com/nodejs/node/pull/46718", "description": "The API is no longer experimental." }, { "version": [ "v18.11.0", "v16.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/44631", "description": "Add support for default values in input `config`." }, { "version": [ "v18.7.0", "v16.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/43459", "description": "add support for returning detailed parse information using `tokens` in input `config` and returned properties." } ] }, "signatures": [ { "params": [ { "textRaw": "`config` {Object} Used to provide arguments for parsing and to configure the parser. `config` supports the following properties:", "name": "config", "type": "Object", "desc": "Used to provide arguments for parsing and to configure the parser. `config` supports the following properties:", "options": [ { "textRaw": "`args` {string[]} array of argument strings. **Default:** `process.argv` with `execPath` and `filename` removed.", "name": "args", "type": "string[]", "default": "`process.argv` with `execPath` and `filename` removed", "desc": "array of argument strings." }, { "textRaw": "`options` {Object} Used to describe arguments known to the parser. Keys of `options` are the long names of options and values are an {Object} accepting the following properties:", "name": "options", "type": "Object", "desc": "Used to describe arguments known to the parser. Keys of `options` are the long names of options and values are an {Object} accepting the following properties:", "options": [ { "textRaw": "`type` {string} Type of argument, which must be either `boolean` or `string`.", "name": "type", "type": "string", "desc": "Type of argument, which must be either `boolean` or `string`." }, { "textRaw": "`multiple` {boolean} Whether this option can be provided multiple times. If `true`, all values will be collected in an array. If `false`, values for the option are last-wins. **Default:** `false`.", "name": "multiple", "type": "boolean", "default": "`false`", "desc": "Whether this option can be provided multiple times. If `true`, all values will be collected in an array. If `false`, values for the option are last-wins." }, { "textRaw": "`short` {string} A single character alias for the option.", "name": "short", "type": "string", "desc": "A single character alias for the option." }, { "textRaw": "`default` {string|boolean|string[]|boolean[]} The value to assign to the option if it does not appear in the arguments to be parsed. The value must match the type specified by the `type` property. If `multiple` is `true`, it must be an array. No default value is applied when the option does appear in the arguments to be parsed, even if the provided value is falsy.", "name": "default", "type": "string|boolean|string[]|boolean[]", "desc": "The value to assign to the option if it does not appear in the arguments to be parsed. The value must match the type specified by the `type` property. If `multiple` is `true`, it must be an array. No default value is applied when the option does appear in the arguments to be parsed, even if the provided value is falsy." } ] }, { "textRaw": "`strict` {boolean} Should an error be thrown when unknown arguments are encountered, or when arguments are passed that do not match the `type` configured in `options`. **Default:** `true`.", "name": "strict", "type": "boolean", "default": "`true`", "desc": "Should an error be thrown when unknown arguments are encountered, or when arguments are passed that do not match the `type` configured in `options`." }, { "textRaw": "`allowPositionals` {boolean} Whether this command accepts positional arguments. **Default:** `false` if `strict` is `true`, otherwise `true`.", "name": "allowPositionals", "type": "boolean", "default": "`false` if `strict` is `true`, otherwise `true`", "desc": "Whether this command accepts positional arguments." }, { "textRaw": "`allowNegative` {boolean} If `true`, allows explicitly setting boolean options to `false` by prefixing the option name with `--no-`. **Default:** `false`.", "name": "allowNegative", "type": "boolean", "default": "`false`", "desc": "If `true`, allows explicitly setting boolean options to `false` by prefixing the option name with `--no-`." }, { "textRaw": "`tokens` {boolean} Return the parsed tokens. This is useful for extending the built-in behavior, from adding additional checks through to reprocessing the tokens in different ways. **Default:** `false`.", "name": "tokens", "type": "boolean", "default": "`false`", "desc": "Return the parsed tokens. This is useful for extending the built-in behavior, from adding additional checks through to reprocessing the tokens in different ways." } ], "optional": true } ], "return": { "textRaw": "Returns: {Object} The parsed command line arguments:", "name": "return", "type": "Object", "desc": "The parsed command line arguments:", "options": [ { "textRaw": "`values` {Object} A mapping of parsed option names with their {string} or {boolean} values.", "name": "values", "type": "Object", "desc": "A mapping of parsed option names with their {string} or {boolean} values." }, { "textRaw": "`positionals` {string[]} Positional arguments.", "name": "positionals", "type": "string[]", "desc": "Positional arguments." }, { "textRaw": "`tokens` {Object[]|undefined} See parseArgs tokens section. Only returned if `config` includes `tokens: true`.", "name": "tokens", "type": "Object[]|undefined", "desc": "See parseArgs tokens section. Only returned if `config` includes `tokens: true`." } ] } } ], "desc": "
Provides a higher level API for command-line argument parsing than interacting\nwith process.argv directly. Takes a specification for the expected arguments\nand returns a structured object with the parsed options and positionals.
\n
import { parseArgs } from 'node:util';\nconst args = ['-f', '--bar', 'b'];\nconst options = {\n foo: {\n type: 'boolean',\n short: 'f',\n },\n bar: {\n type: 'string',\n },\n};\nconst {\n values,\n positionals,\n} = parseArgs({ args, options });\nconsole.log(values, positionals);\n// Prints: [Object: null prototype] { foo: true, bar: 'b' } []\n\n
const { parseArgs } = require('node:util');\nconst args = ['-f', '--bar', 'b'];\nconst options = {\n foo: {\n type: 'boolean',\n short: 'f',\n },\n bar: {\n type: 'string',\n },\n};\nconst {\n values,\n positionals,\n} = parseArgs({ args, options });\nconsole.log(values, positionals);\n// Prints: [Object: null prototype] { foo: true, bar: 'b' } []\n", "modules": [ { "textRaw": "`parseArgs` `tokens`", "name": "`parseargs`_`tokens`", "type": "module", "desc": "
Detailed parse information is available for adding custom behaviors by\nspecifying tokens: true in the configuration.\nThe returned tokens have properties describing:
\n
name <string> Long name of option.rawName <string> How option used in args, like -f of --foo.value <string> | <undefined> Option value specified in args.\nUndefined for boolean options.inlineValue <boolean> | <undefined> Whether option value specified inline,\nlike --foo=bar.value <string> The value of the positional argument in args (i.e. args[index]).\n
The returned tokens are in the order encountered in the input args. Options\nthat appear more than once in args produce a token for each use. Short option\ngroups like -xy expand to a token for each option. So -xxx produces\nthree tokens.
\n
For example, to add support for a negated option like --no-color (which\nallowNegative supports when the option is of boolean type), the returned\ntokens can be reprocessed to change the value stored for the negated option.
\n
import { parseArgs } from 'node:util';\n\nconst options = {\n 'color': { type: 'boolean' },\n 'no-color': { type: 'boolean' },\n 'logfile': { type: 'string' },\n 'no-logfile': { type: 'boolean' },\n};\nconst { values, tokens } = parseArgs({ options, tokens: true });\n\n// Reprocess the option tokens and overwrite the returned values.\ntokens\n .filter((token) => token.kind === 'option')\n .forEach((token) => {\n if (token.name.startsWith('no-')) {\n // Store foo:false for --no-foo\n const positiveName = token.name.slice(3);\n values[positiveName] = false;\n delete values[token.name];\n } else {\n // Resave value so last one wins if both --foo and --no-foo.\n values[token.name] = token.value ?? true;\n }\n });\n\nconst color = values.color;\nconst logfile = values.logfile ?? 'default.log';\n\nconsole.log({ logfile, color });\n\n
const { parseArgs } = require('node:util');\n\nconst options = {\n 'color': { type: 'boolean' },\n 'no-color': { type: 'boolean' },\n 'logfile': { type: 'string' },\n 'no-logfile': { type: 'boolean' },\n};\nconst { values, tokens } = parseArgs({ options, tokens: true });\n\n// Reprocess the option tokens and overwrite the returned values.\ntokens\n .filter((token) => token.kind === 'option')\n .forEach((token) => {\n if (token.name.startsWith('no-')) {\n // Store foo:false for --no-foo\n const positiveName = token.name.slice(3);\n values[positiveName] = false;\n delete values[token.name];\n } else {\n // Resave value so last one wins if both --foo and --no-foo.\n values[token.name] = token.value ?? true;\n }\n });\n\nconst color = values.color;\nconst logfile = values.logfile ?? 'default.log';\n\nconsole.log({ logfile, color });\n\n
Example usage showing negated options, and when an option is used\nmultiple ways then last one wins.
\n
$ node negate.js\n{ logfile: 'default.log', color: undefined }\n$ node negate.js --no-logfile --no-color\n{ logfile: false, color: false }\n$ node negate.js --logfile=test.log --color\n{ logfile: 'test.log', color: true }\n$ node negate.js --no-logfile --logfile=test.log --color --no-color\n{ logfile: 'test.log', color: false }\n", "displayName": "`parseArgs` `tokens`" } ] }, { "textRaw": "`util.parseEnv(content)`", "name": "parseEnv", "type": "method", "meta": { "added": [ "v21.7.0", "v20.12.0" ], "changes": [ { "version": [ "v24.10.0", "v22.21.0" ], "pr-url": "https://github.com/nodejs/node/pull/59925", "description": "This API is no longer experimental." } ] }, "signatures": [ { "params": [ { "textRaw": "`content` {string}", "name": "content", "type": "string" } ] } ], "desc": "
The raw contents of a .env file.
\n
<Object>\n
Given an example .env file:
\n
const { parseEnv } = require('node:util');\n\nparseEnv('HELLO=world\\nHELLO=oh my\\n');\n// Returns: { HELLO: 'oh my' }\n\n
import { parseEnv } from 'node:util';\n\nparseEnv('HELLO=world\\nHELLO=oh my\\n');\n// Returns: { HELLO: 'oh my' }\n" }, { "textRaw": "`util.promisify(original)`", "name": "promisify", "type": "method", "meta": { "added": [ "v8.0.0" ], "changes": [ { "version": "v20.8.0", "pr-url": "https://github.com/nodejs/node/pull/49647", "description": "Calling `promisify` on a function that returns a `Promise` is deprecated." } ] }, "signatures": [ { "params": [ { "textRaw": "`original` {Function}", "name": "original", "type": "Function" } ], "return": { "textRaw": "Returns: {Function}", "name": "return", "type": "Function" } } ], "desc": "
Takes a function following the common error-first callback style, i.e. taking\nan (err, value) => ... callback as the last argument, and returns a version\nthat returns promises.
\n
import { promisify } from 'node:util';\nimport { stat } from 'node:fs';\n\nconst promisifiedStat = promisify(stat);\npromisifiedStat('.').then((stats) => {\n // Do something with `stats`\n}).catch((error) => {\n // Handle the error.\n});\n\n
const { promisify } = require('node:util');\nconst { stat } = require('node:fs');\n\nconst promisifiedStat = promisify(stat);\npromisifiedStat('.').then((stats) => {\n // Do something with `stats`\n}).catch((error) => {\n // Handle the error.\n});\n\n
Or, equivalently using async functions:
\n
import { promisify } from 'node:util';\nimport { stat } from 'node:fs';\n\nconst promisifiedStat = promisify(stat);\n\nasync function callStat() {\n const stats = await promisifiedStat('.');\n console.log(`This directory is owned by ${stats.uid}`);\n}\n\ncallStat();\n\n
const { promisify } = require('node:util');\nconst { stat } = require('node:fs');\n\nconst promisifiedStat = promisify(stat);\n\nasync function callStat() {\n const stats = await promisifiedStat('.');\n console.log(`This directory is owned by ${stats.uid}`);\n}\n\ncallStat();\n\n
If there is an original[util.promisify.custom] property present, promisify\nwill return its value, see Custom promisified functions.
\n
promisify() assumes that original is a function taking a callback as its\nfinal argument in all cases. If original is not a function, promisify()\nwill throw an error. If original is a function but its last argument is not\nan error-first callback, it will still be passed an error-first\ncallback as its last argument.
\n
Using promisify() on class methods or other methods that use this may not\nwork as expected unless handled specially:
\n
import { promisify } from 'node:util';\n\nclass Foo {\n constructor() {\n this.a = 42;\n }\n\n bar(callback) {\n callback(null, this.a);\n }\n}\n\nconst foo = new Foo();\n\nconst naiveBar = promisify(foo.bar);\n// TypeError: Cannot read properties of undefined (reading 'a')\n// naiveBar().then(a => console.log(a));\n\nnaiveBar.call(foo).then((a) => console.log(a)); // '42'\n\nconst bindBar = naiveBar.bind(foo);\nbindBar().then((a) => console.log(a)); // '42'\n\n
const { promisify } = require('node:util');\n\nclass Foo {\n constructor() {\n this.a = 42;\n }\n\n bar(callback) {\n callback(null, this.a);\n }\n}\n\nconst foo = new Foo();\n\nconst naiveBar = promisify(foo.bar);\n// TypeError: Cannot read properties of undefined (reading 'a')\n// naiveBar().then(a => console.log(a));\n\nnaiveBar.call(foo).then((a) => console.log(a)); // '42'\n\nconst bindBar = naiveBar.bind(foo);\nbindBar().then((a) => console.log(a)); // '42'\n", "modules": [ { "textRaw": "Custom promisified functions", "name": "custom_promisified_functions", "type": "module", "desc": "
Using the util.promisify.custom symbol one can override the return value of\nutil.promisify():
\n
import { promisify } from 'node:util';\n\nfunction doSomething(foo, callback) {\n // ...\n}\n\ndoSomething[promisify.custom] = (foo) => {\n return getPromiseSomehow();\n};\n\nconst promisified = promisify(doSomething);\nconsole.log(promisified === doSomething[promisify.custom]);\n// prints 'true'\n\n
const { promisify } = require('node:util');\n\nfunction doSomething(foo, callback) {\n // ...\n}\n\ndoSomething[promisify.custom] = (foo) => {\n return getPromiseSomehow();\n};\n\nconst promisified = promisify(doSomething);\nconsole.log(promisified === doSomething[promisify.custom]);\n// prints 'true'\n\n
This can be useful for cases where the original function does not follow the\nstandard format of taking an error-first callback as the last argument.
\n
For example, with a function that takes in\n(foo, onSuccessCallback, onErrorCallback):
\n
doSomething[util.promisify.custom] = (foo) => {\n return new Promise((resolve, reject) => {\n doSomething(foo, resolve, reject);\n });\n};\n\n
If promisify.custom is defined but is not a function, promisify() will\nthrow an error.
", "displayName": "Custom promisified functions" } ], "properties": [ { "textRaw": "Type: {symbol} that can be used to declare custom promisified variants of functions, see Custom promisified functions.", "name": "custom", "type": "symbol", "meta": { "added": [ "v8.0.0" ], "changes": [ { "version": [ "v13.12.0", "v12.16.2" ], "pr-url": "https://github.com/nodejs/node/pull/31672", "description": "This is now defined as a shared symbol." } ] }, "desc": "
In addition to being accessible through util.promisify.custom, this\nsymbol is registered globally and can be\naccessed in any environment as Symbol.for('nodejs.util.promisify.custom').
\n
For example, with a function that takes in\n(foo, onSuccessCallback, onErrorCallback):
\n
const kCustomPromisifiedSymbol = Symbol.for('nodejs.util.promisify.custom');\n\ndoSomething[kCustomPromisifiedSymbol] = (foo) => {\n return new Promise((resolve, reject) => {\n doSomething(foo, resolve, reject);\n });\n};\n", "shortDesc": "that can be used to declare custom promisified variants of functions, see Custom promisified functions." } ] }, { "textRaw": "`util.stripVTControlCharacters(str)`", "name": "stripVTControlCharacters", "type": "method", "meta": { "added": [ "v16.11.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`str` {string}", "name": "str", "type": "string" } ], "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" } } ], "desc": "
Returns str with any ANSI escape codes removed.
\n
console.log(util.stripVTControlCharacters('\\u001B[4mvalue\\u001B[0m'));\n// Prints \"value\"\n" }, { "textRaw": "`util.styleText(format, text[, options])`", "name": "styleText", "type": "method", "meta": { "added": [ "v21.7.0", "v20.12.0" ], "changes": [ { "version": "v26.1.0", "pr-url": "https://github.com/nodejs/node/pull/61556", "description": "Add support for hexadecimal colors." }, { "version": [ "v24.2.0", "v22.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/58437", "description": "Added the `'none'` format as a non-op format." }, { "version": [ "v23.5.0", "v22.13.0" ], "pr-url": "https://github.com/nodejs/node/pull/56265", "description": "styleText is now stable." }, { "version": [ "v22.8.0", "v20.18.0" ], "pr-url": "https://github.com/nodejs/node/pull/54389", "description": "Respect isTTY and environment variables such as NO_COLOR, NODE_DISABLE_COLORS, and FORCE_COLOR." } ] }, "signatures": [ { "params": [ { "textRaw": "`format` {string|Array} A text format or an Array of text formats defined in `util.inspect.colors`, or a hex color in `#RGB` or `#RRGGBB` form.", "name": "format", "type": "string|Array", "desc": "A text format or an Array of text formats defined in `util.inspect.colors`, or a hex color in `#RGB` or `#RRGGBB` form." }, { "textRaw": "`text` {string} The text to be formatted.", "name": "text", "type": "string", "desc": "The text to be formatted." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`validateStream` {boolean} When true, `stream` is checked to see if it can handle colors. **Default:** `true`.", "name": "validateStream", "type": "boolean", "default": "`true`", "desc": "When true, `stream` is checked to see if it can handle colors." }, { "textRaw": "`stream` {Stream} A stream that will be validated if it can be colored. **Default:** `process.stdout`.", "name": "stream", "type": "Stream", "default": "`process.stdout`", "desc": "A stream that will be validated if it can be colored." } ], "optional": true } ] } ], "desc": "
This function returns a formatted text considering the format passed\nfor printing in a terminal. It is aware of the terminal's capabilities\nand acts according to the configuration set via NO_COLOR,\nNODE_DISABLE_COLORS and FORCE_COLOR environment variables.
\n
import { styleText } from 'node:util';\nimport { stderr } from 'node:process';\n\nconst successMessage = styleText('green', 'Success!');\nconsole.log(successMessage);\n\nconst errorMessage = styleText(\n 'red',\n 'Error! Error!',\n // Validate if process.stderr has TTY\n { stream: stderr },\n);\nconsole.error(errorMessage);\n\n
const { styleText } = require('node:util');\nconst { stderr } = require('node:process');\n\nconst successMessage = styleText('green', 'Success!');\nconsole.log(successMessage);\n\nconst errorMessage = styleText(\n 'red',\n 'Error! Error!',\n // Validate if process.stderr has TTY\n { stream: stderr },\n);\nconsole.error(errorMessage);\n\n
util.inspect.colors also provides text formats such as italic, and\nunderline and you can combine both:
\n
console.log(\n util.styleText(['underline', 'italic'], 'My italic underlined message'),\n);\n\n
When passing an array of formats, the order of the format applied\nis left to right so the following style might overwrite the previous one.
\n
console.log(\n util.styleText(['red', 'green'], 'text'), // green\n);\n\n
The special format value none applies no additional styling to the text.
\n
In addition to predefined color names, util.styleText() supports hex color\nstrings using ANSI TrueColor (24-bit) escape sequences. Hex colors can be\nspecified in either 3-digit (#RGB) or 6-digit (#RRGGBB) format:
\n
import { styleText } from 'node:util';\n\n// 6-digit hex color\nconsole.log(styleText('#ff5733', 'Orange text'));\n\n// 3-digit hex color (shorthand)\nconsole.log(styleText('#f00', 'Red text'));\n\n
const { styleText } = require('node:util');\n\n// 6-digit hex color\nconsole.log(styleText('#ff5733', 'Orange text'));\n\n// 3-digit hex color (shorthand)\nconsole.log(styleText('#f00', 'Red text'));\n\n
The full list of formats can be found in modifiers.
" }, { "textRaw": "`util.toUSVString(string)`", "name": "toUSVString", "type": "method", "meta": { "added": [ "v16.8.0", "v14.18.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`string` {string}", "name": "string", "type": "string" } ] } ], "desc": "
Returns the string after replacing any surrogate code points\n(or equivalently, any unpaired surrogate code units) with the\nUnicode \"replacement character\" U+FFFD.
" }, { "textRaw": "`util.transferableAbortController()`", "name": "transferableAbortController", "type": "method", "meta": { "added": [ "v18.11.0" ], "changes": [ { "version": [ "v23.11.0", "v22.15.0" ], "pr-url": "https://github.com/nodejs/node/pull/57510", "description": "Marking the API stable." } ] }, "signatures": [ { "params": [] } ], "desc": "
Creates and returns an <AbortController> instance whose <AbortSignal> is marked\nas transferable and can be used with structuredClone() or postMessage().
" }, { "textRaw": "`util.transferableAbortSignal(signal)`", "name": "transferableAbortSignal", "type": "method", "meta": { "added": [ "v18.11.0" ], "changes": [ { "version": [ "v23.11.0", "v22.15.0" ], "pr-url": "https://github.com/nodejs/node/pull/57510", "description": "Marking the API stable." } ] }, "signatures": [ { "params": [ { "textRaw": "`signal` {AbortSignal}", "name": "signal", "type": "AbortSignal" } ], "return": { "textRaw": "Returns: {AbortSignal}", "name": "return", "type": "AbortSignal" } } ], "desc": "
Marks the given <AbortSignal> as transferable so that it can be used with structuredClone() and postMessage().
\n
const signal = transferableAbortSignal(AbortSignal.timeout(100));\nconst channel = new MessageChannel();\nchannel.port2.postMessage(signal, [signal]);\n" }, { "textRaw": "`util.aborted(signal, resource)`", "name": "aborted", "type": "method", "meta": { "added": [ "v19.7.0", "v18.16.0" ], "changes": [ { "version": [ "v24.0.0", "v22.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/57765", "description": "Change stability index for this feature from Experimental to Stable." } ] }, "signatures": [ { "params": [ { "textRaw": "`signal` {AbortSignal}", "name": "signal", "type": "AbortSignal" }, { "textRaw": "`resource` {Object} Any non-null object tied to the abortable operation and held weakly. If `resource` is garbage collected before the `signal` aborts, the promise remains pending, allowing Node.js to stop tracking it. This helps prevent memory leaks in long-running or non-cancelable operations.", "name": "resource", "type": "Object", "desc": "Any non-null object tied to the abortable operation and held weakly. If `resource` is garbage collected before the `signal` aborts, the promise remains pending, allowing Node.js to stop tracking it. This helps prevent memory leaks in long-running or non-cancelable operations." } ], "return": { "textRaw": "Returns: {Promise}", "name": "return", "type": "Promise" } } ], "desc": "
Listens to abort event on the provided signal and returns a promise that resolves when the signal is aborted.\nIf resource is provided, it weakly references the operation's associated object,\nso if resource is garbage collected before the signal aborts,\nthen returned promise shall remain pending.\nThis prevents memory leaks in long-running or non-cancelable operations.
\n
const { aborted } = require('node:util');\n\n// Obtain an object with an abortable signal, like a custom resource or operation.\nconst dependent = obtainSomethingAbortable();\n\n// Pass `dependent` as the resource, indicating the promise should only resolve\n// if `dependent` is still in memory when the signal is aborted.\naborted(dependent.signal, dependent).then(() => {\n\n // This code runs when `dependent` is aborted.\n console.log('Dependent resource was aborted.');\n});\n\n// Simulate an event that triggers the abort.\ndependent.on('event', () => {\n dependent.abort(); // This will cause the `aborted` promise to resolve.\n});\n\n
import { aborted } from 'node:util';\n\n// Obtain an object with an abortable signal, like a custom resource or operation.\nconst dependent = obtainSomethingAbortable();\n\n// Pass `dependent` as the resource, indicating the promise should only resolve\n// if `dependent` is still in memory when the signal is aborted.\naborted(dependent.signal, dependent).then(() => {\n\n // This code runs when `dependent` is aborted.\n console.log('Dependent resource was aborted.');\n});\n\n// Simulate an event that triggers the abort.\ndependent.on('event', () => {\n dependent.abort(); // This will cause the `aborted` promise to resolve.\n});\n" } ], "classes": [ { "textRaw": "Class: `util.MIMEType`", "name": "util.MIMEType", "type": "class", "meta": { "added": [ "v19.1.0", "v18.13.0" ], "changes": [ { "version": [ "v23.11.0", "v22.15.0" ], "pr-url": "https://github.com/nodejs/node/pull/57510", "description": "Marking the API stable." } ] }, "desc": "
An implementation of the MIMEType class.
\n
In accordance with browser conventions, all properties of MIMEType objects\nare implemented as getters and setters on the class prototype, rather than as\ndata properties on the object itself.
\n
A MIME string is a structured string containing multiple meaningful\ncomponents. When parsed, a MIMEType object is returned containing\nproperties for each of these components.
", "signatures": [ { "textRaw": "`new MIMEType(input)`", "name": "MIMEType", "type": "ctor", "params": [ { "textRaw": "`input` {string} The input MIME to parse", "name": "input", "type": "string", "desc": "The input MIME to parse" } ], "desc": "
Creates a new MIMEType object by parsing the input.
\n
import { MIMEType } from 'node:util';\n\nconst myMIME = new MIMEType('text/plain');\n\n
const { MIMEType } = require('node:util');\n\nconst myMIME = new MIMEType('text/plain');\n\n
A TypeError will be thrown if the input is not a valid MIME. Note\nthat an effort will be made to coerce the given values into strings. For\ninstance:
\n
import { MIMEType } from 'node:util';\nconst myMIME = new MIMEType({ toString: () => 'text/plain' });\nconsole.log(String(myMIME));\n// Prints: text/plain\n\n
const { MIMEType } = require('node:util');\nconst myMIME = new MIMEType({ toString: () => 'text/plain' });\nconsole.log(String(myMIME));\n// Prints: text/plain\n" } ], "properties": [ { "textRaw": "Type: {string}", "name": "type", "type": "string", "desc": "
Gets and sets the type portion of the MIME.
\n
import { MIMEType } from 'node:util';\n\nconst myMIME = new MIMEType('text/javascript');\nconsole.log(myMIME.type);\n// Prints: text\nmyMIME.type = 'application';\nconsole.log(myMIME.type);\n// Prints: application\nconsole.log(String(myMIME));\n// Prints: application/javascript\n\n
const { MIMEType } = require('node:util');\n\nconst myMIME = new MIMEType('text/javascript');\nconsole.log(myMIME.type);\n// Prints: text\nmyMIME.type = 'application';\nconsole.log(myMIME.type);\n// Prints: application\nconsole.log(String(myMIME));\n// Prints: application/javascript\n" }, { "textRaw": "Type: {string}", "name": "subtype", "type": "string", "desc": "
Gets and sets the subtype portion of the MIME.
\n
import { MIMEType } from 'node:util';\n\nconst myMIME = new MIMEType('text/ecmascript');\nconsole.log(myMIME.subtype);\n// Prints: ecmascript\nmyMIME.subtype = 'javascript';\nconsole.log(myMIME.subtype);\n// Prints: javascript\nconsole.log(String(myMIME));\n// Prints: text/javascript\n\n
const { MIMEType } = require('node:util');\n\nconst myMIME = new MIMEType('text/ecmascript');\nconsole.log(myMIME.subtype);\n// Prints: ecmascript\nmyMIME.subtype = 'javascript';\nconsole.log(myMIME.subtype);\n// Prints: javascript\nconsole.log(String(myMIME));\n// Prints: text/javascript\n" }, { "textRaw": "Type: {string}", "name": "essence", "type": "string", "desc": "
Gets the essence of the MIME. This property is read only.\nUse mime.type or mime.subtype to alter the MIME.
\n
import { MIMEType } from 'node:util';\n\nconst myMIME = new MIMEType('text/javascript;key=value');\nconsole.log(myMIME.essence);\n// Prints: text/javascript\nmyMIME.type = 'application';\nconsole.log(myMIME.essence);\n// Prints: application/javascript\nconsole.log(String(myMIME));\n// Prints: application/javascript;key=value\n\n
const { MIMEType } = require('node:util');\n\nconst myMIME = new MIMEType('text/javascript;key=value');\nconsole.log(myMIME.essence);\n// Prints: text/javascript\nmyMIME.type = 'application';\nconsole.log(myMIME.essence);\n// Prints: application/javascript\nconsole.log(String(myMIME));\n// Prints: application/javascript;key=value\n" }, { "textRaw": "Type: {MIMEParams}", "name": "params", "type": "MIMEParams", "desc": "
Gets the MIMEParams object representing the\nparameters of the MIME. This property is read-only. See\nMIMEParams documentation for details.
" } ], "methods": [ { "textRaw": "`mime.toString()`", "name": "toString", "type": "method", "signatures": [ { "params": [], "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" } } ], "desc": "
The toString() method on the MIMEType object returns the serialized MIME.
\n
Because of the need for standard compliance, this method does not allow users\nto customize the serialization process of the MIME.
" }, { "textRaw": "`mime.toJSON()`", "name": "toJSON", "type": "method", "signatures": [ { "params": [], "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" } } ], "desc": "
Alias for mime.toString().
\n
This method is automatically called when an MIMEType object is serialized\nwith JSON.stringify().
\n
import { MIMEType } from 'node:util';\n\nconst myMIMES = [\n new MIMEType('image/png'),\n new MIMEType('image/gif'),\n];\nconsole.log(JSON.stringify(myMIMES));\n// Prints: [\"image/png\", \"image/gif\"]\n\n
const { MIMEType } = require('node:util');\n\nconst myMIMES = [\n new MIMEType('image/png'),\n new MIMEType('image/gif'),\n];\nconsole.log(JSON.stringify(myMIMES));\n// Prints: [\"image/png\", \"image/gif\"]\n" } ] }, { "textRaw": "Class: `util.MIMEParams`", "name": "util.MIMEParams", "type": "class", "meta": { "added": [ "v19.1.0", "v18.13.0" ], "changes": [] }, "desc": "
The MIMEParams API provides read and write access to the parameters of a\nMIMEType.
", "signatures": [ { "textRaw": "`new MIMEParams()`", "name": "MIMEParams", "type": "ctor", "params": [], "desc": "
Creates a new MIMEParams object by with empty parameters
\n
import { MIMEParams } from 'node:util';\n\nconst myParams = new MIMEParams();\n\n
const { MIMEParams } = require('node:util');\n\nconst myParams = new MIMEParams();\n" } ], "methods": [ { "textRaw": "`mimeParams.delete(name)`", "name": "delete", "type": "method", "signatures": [ { "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ] } ], "desc": "
Remove all name-value pairs whose name is name.
" }, { "textRaw": "`mimeParams.entries()`", "name": "entries", "type": "method", "signatures": [ { "params": [], "return": { "textRaw": "Returns: {Iterator}", "name": "return", "type": "Iterator" } } ], "desc": "
Returns an iterator over each of the name-value pairs in the parameters.\nEach item of the iterator is a JavaScript Array. The first item of the array\nis the name, the second item of the array is the value.
" }, { "textRaw": "`mimeParams.get(name)`", "name": "get", "type": "method", "signatures": [ { "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ], "return": { "textRaw": "Returns: {string|null} A string or `null` if there is no name-value pair with the given `name`.", "name": "return", "type": "string|null", "desc": "A string or `null` if there is no name-value pair with the given `name`." } } ], "desc": "
Returns the value of the first name-value pair whose name is name. If there\nare no such pairs, null is returned.
" }, { "textRaw": "`mimeParams.has(name)`", "name": "has", "type": "method", "signatures": [ { "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if there is at least one name-value pair whose name is name.
" }, { "textRaw": "`mimeParams.keys()`", "name": "keys", "type": "method", "signatures": [ { "params": [], "return": { "textRaw": "Returns: {Iterator}", "name": "return", "type": "Iterator" } } ], "desc": "
Returns an iterator over the names of each name-value pair.
\n
import { MIMEType } from 'node:util';\n\nconst { params } = new MIMEType('text/plain;foo=0;bar=1');\nfor (const name of params.keys()) {\n console.log(name);\n}\n// Prints:\n// foo\n// bar\n\n
const { MIMEType } = require('node:util');\n\nconst { params } = new MIMEType('text/plain;foo=0;bar=1');\nfor (const name of params.keys()) {\n console.log(name);\n}\n// Prints:\n// foo\n// bar\n" }, { "textRaw": "`mimeParams.set(name, value)`", "name": "set", "type": "method", "signatures": [ { "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" }, { "textRaw": "`value` {string}", "name": "value", "type": "string" } ] } ], "desc": "
Sets the value in the MIMEParams object associated with name to\nvalue. If there are any pre-existing name-value pairs whose names are name,\nset the first such pair's value to value.
\n
import { MIMEType } from 'node:util';\n\nconst { params } = new MIMEType('text/plain;foo=0;bar=1');\nparams.set('foo', 'def');\nparams.set('baz', 'xyz');\nconsole.log(params.toString());\n// Prints: foo=def;bar=1;baz=xyz\n\n
const { MIMEType } = require('node:util');\n\nconst { params } = new MIMEType('text/plain;foo=0;bar=1');\nparams.set('foo', 'def');\nparams.set('baz', 'xyz');\nconsole.log(params.toString());\n// Prints: foo=def;bar=1;baz=xyz\n" }, { "textRaw": "`mimeParams.values()`", "name": "values", "type": "method", "signatures": [ { "params": [], "return": { "textRaw": "Returns: {Iterator}", "name": "return", "type": "Iterator" } } ], "desc": "
Returns an iterator over the values of each name-value pair.
" }, { "textRaw": "`mimeParams[Symbol.iterator]()`", "name": "[Symbol.iterator]", "type": "method", "signatures": [ { "params": [], "return": { "textRaw": "Returns: {Iterator}", "name": "return", "type": "Iterator" } } ], "desc": "
Alias for mimeParams.entries().
\n
import { MIMEType } from 'node:util';\n\nconst { params } = new MIMEType('text/plain;foo=bar;xyz=baz');\nfor (const [name, value] of params) {\n console.log(name, value);\n}\n// Prints:\n// foo bar\n// xyz baz\n\n
const { MIMEType } = require('node:util');\n\nconst { params } = new MIMEType('text/plain;foo=bar;xyz=baz');\nfor (const [name, value] of params) {\n console.log(name, value);\n}\n// Prints:\n// foo bar\n// xyz baz\n" } ] }, { "textRaw": "Class: `util.TextDecoder`", "name": "util.TextDecoder", "type": "class", "meta": { "added": [ "v8.3.0" ], "changes": [ { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/22281", "description": "The class is now available on the global object." } ] }, "desc": "
An implementation of the WHATWG Encoding Standard TextDecoder API.
\n
const decoder = new TextDecoder();\nconst u8arr = new Uint8Array([72, 101, 108, 108, 111]);\nconsole.log(decoder.decode(u8arr)); // Hello\n", "modules": [ { "textRaw": "WHATWG supported encodings", "name": "whatwg_supported_encodings", "type": "module", "desc": "
Per the WHATWG Encoding Standard, the encodings supported by the\nTextDecoder API are outlined in the tables below. For each encoding,\none or more aliases may be used.
\n
Different Node.js build configurations support different sets of encodings.\n(see Internationalization)
", "modules": [ { "textRaw": "Encodings supported by default (with full ICU data)", "name": "encodings_supported_by_default_(with_full_icu_data)", "type": "module", "desc": "
| Encoding | \nAliases | \n
|---|---|
'ibm866' | \n'866', 'cp866', 'csibm866' | \n
'iso-8859-2' | \n'csisolatin2', 'iso-ir-101', 'iso8859-2', 'iso88592', 'iso_8859-2', 'iso_8859-2:1987', 'l2', 'latin2' | \n
'iso-8859-3' | \n'csisolatin3', 'iso-ir-109', 'iso8859-3', 'iso88593', 'iso_8859-3', 'iso_8859-3:1988', 'l3', 'latin3' | \n
'iso-8859-4' | \n'csisolatin4', 'iso-ir-110', 'iso8859-4', 'iso88594', 'iso_8859-4', 'iso_8859-4:1988', 'l4', 'latin4' | \n
'iso-8859-5' | \n'csisolatincyrillic', 'cyrillic', 'iso-ir-144', 'iso8859-5', 'iso88595', 'iso_8859-5', 'iso_8859-5:1988' | \n
'iso-8859-6' | \n'arabic', 'asmo-708', 'csiso88596e', 'csiso88596i', 'csisolatinarabic', 'ecma-114', 'iso-8859-6-e', 'iso-8859-6-i', 'iso-ir-127', 'iso8859-6', 'iso88596', 'iso_8859-6', 'iso_8859-6:1987' | \n
'iso-8859-7' | \n'csisolatingreek', 'ecma-118', 'elot_928', 'greek', 'greek8', 'iso-ir-126', 'iso8859-7', 'iso88597', 'iso_8859-7', 'iso_8859-7:1987', 'sun_eu_greek' | \n
'iso-8859-8' | \n'csiso88598e', 'csisolatinhebrew', 'hebrew', 'iso-8859-8-e', 'iso-ir-138', 'iso8859-8', 'iso88598', 'iso_8859-8', 'iso_8859-8:1988', 'visual' | \n
'iso-8859-8-i' | \n'csiso88598i', 'logical' | \n
'iso-8859-10' | \n'csisolatin6', 'iso-ir-157', 'iso8859-10', 'iso885910', 'l6', 'latin6' | \n
'iso-8859-13' | \n'iso8859-13', 'iso885913' | \n
'iso-8859-14' | \n'iso8859-14', 'iso885914' | \n
'iso-8859-15' | \n'csisolatin9', 'iso8859-15', 'iso885915', 'iso_8859-15', 'l9' | \n
'koi8-r' | \n'cskoi8r', 'koi', 'koi8', 'koi8_r' | \n
'koi8-u' | \n'koi8-ru' | \n
'macintosh' | \n'csmacintosh', 'mac', 'x-mac-roman' | \n
'windows-874' | \n'dos-874', 'iso-8859-11', 'iso8859-11', 'iso885911', 'tis-620' | \n
'windows-1250' | \n'cp1250', 'x-cp1250' | \n
'windows-1251' | \n'cp1251', 'x-cp1251' | \n
'windows-1252' | \n'ansi_x3.4-1968', 'ascii', 'cp1252', 'cp819', 'csisolatin1', 'ibm819', 'iso-8859-1', 'iso-ir-100', 'iso8859-1', 'iso88591', 'iso_8859-1', 'iso_8859-1:1987', 'l1', 'latin1', 'us-ascii', 'x-cp1252' | \n
'windows-1253' | \n'cp1253', 'x-cp1253' | \n
'windows-1254' | \n'cp1254', 'csisolatin5', 'iso-8859-9', 'iso-ir-148', 'iso8859-9', 'iso88599', 'iso_8859-9', 'iso_8859-9:1989', 'l5', 'latin5', 'x-cp1254' | \n
'windows-1255' | \n'cp1255', 'x-cp1255' | \n
'windows-1256' | \n'cp1256', 'x-cp1256' | \n
'windows-1257' | \n'cp1257', 'x-cp1257' | \n
'windows-1258' | \n'cp1258', 'x-cp1258' | \n
'x-mac-cyrillic' | \n'x-mac-ukrainian' | \n
'gbk' | \n'chinese', 'csgb2312', 'csiso58gb231280', 'gb2312', 'gb_2312', 'gb_2312-80', 'iso-ir-58', 'x-gbk' | \n
'gb18030' | \n\n |
'big5' | \n'big5-hkscs', 'cn-big5', 'csbig5', 'x-x-big5' | \n
'euc-jp' | \n'cseucpkdfmtjapanese', 'x-euc-jp' | \n
'iso-2022-jp' | \n'csiso2022jp' | \n
'shift_jis' | \n'csshiftjis', 'ms932', 'ms_kanji', 'shift-jis', 'sjis', 'windows-31j', 'x-sjis' | \n
'euc-kr' | \n'cseuckr', 'csksc56011987', 'iso-ir-149', 'korean', 'ks_c_5601-1987', 'ks_c_5601-1989', 'ksc5601', 'ksc_5601', 'windows-949' | \n
", "displayName": "Encodings supported by default (with full ICU data)" }, { "textRaw": "Encodings supported when Node.js is built with the `small-icu` option", "name": "encodings_supported_when_node.js_is_built_with_the_`small-icu`_option", "type": "module", "desc": "
| Encoding | \nAliases | \n
|---|---|
'utf-8' | \n'unicode-1-1-utf-8', 'utf8' | \n
'utf-16le' | \n'utf-16' | \n
'utf-16be' | \n\n |
", "displayName": "Encodings supported when Node.js is built with the `small-icu` option" }, { "textRaw": "Encodings supported when ICU is disabled", "name": "encodings_supported_when_icu_is_disabled", "type": "module", "desc": "
| Encoding | \nAliases | \n
|---|---|
'utf-8' | \n'unicode-1-1-utf-8', 'utf8' | \n
'utf-16le' | \n'utf-16' | \n
\n
The 'iso-8859-16' encoding listed in the WHATWG Encoding Standard\nis not supported.
", "displayName": "Encodings supported when ICU is disabled" } ], "displayName": "WHATWG supported encodings" } ], "signatures": [ { "textRaw": "`new TextDecoder([encoding[, options]])`", "name": "TextDecoder", "type": "ctor", "params": [ { "textRaw": "`encoding` {string} Identifies the `encoding` that this `TextDecoder` instance supports. **Default:** `'utf-8'`.", "name": "encoding", "type": "string", "default": "`'utf-8'`", "desc": "Identifies the `encoding` that this `TextDecoder` instance supports.", "optional": true }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`fatal` {boolean} `true` if decoding failures are fatal. This option is not supported when ICU is disabled (see Internationalization). **Default:** `false`.", "name": "fatal", "type": "boolean", "default": "`false`", "desc": "`true` if decoding failures are fatal. This option is not supported when ICU is disabled (see Internationalization)." }, { "textRaw": "`ignoreBOM` {boolean} When `true`, the `TextDecoder` will include the byte order mark in the decoded result. When `false`, the byte order mark will be removed from the output. This option is only used when `encoding` is `'utf-8'`, `'utf-16be'`, or `'utf-16le'`. **Default:** `false`.", "name": "ignoreBOM", "type": "boolean", "default": "`false`", "desc": "When `true`, the `TextDecoder` will include the byte order mark in the decoded result. When `false`, the byte order mark will be removed from the output. This option is only used when `encoding` is `'utf-8'`, `'utf-16be'`, or `'utf-16le'`." } ], "optional": true } ], "desc": "
Creates a new TextDecoder instance. The encoding may specify one of the\nsupported encodings or an alias.
\n
The TextDecoder class is also available on the global object.
" } ], "methods": [ { "textRaw": "`textDecoder.decode([input[, options]])`", "name": "decode", "type": "method", "signatures": [ { "params": [ { "textRaw": "`input` {ArrayBuffer|DataView|TypedArray} An `ArrayBuffer`, `DataView`, or `TypedArray` instance containing the encoded data.", "name": "input", "type": "ArrayBuffer|DataView|TypedArray", "desc": "An `ArrayBuffer`, `DataView`, or `TypedArray` instance containing the encoded data.", "optional": true }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`stream` {boolean} `true` if additional chunks of data are expected. **Default:** `false`.", "name": "stream", "type": "boolean", "default": "`false`", "desc": "`true` if additional chunks of data are expected." } ], "optional": true } ], "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" } } ], "desc": "
Decodes the input and returns a string. If options.stream is true, any\nincomplete byte sequences occurring at the end of the input are buffered\ninternally and emitted after the next call to textDecoder.decode().
\n
If textDecoder.fatal is true, decoding errors that occur will result in a\nTypeError being thrown.
" } ], "properties": [ { "textRaw": "Type: {string}", "name": "encoding", "type": "string", "desc": "
The encoding supported by the TextDecoder instance.
" }, { "textRaw": "Type: {boolean}", "name": "fatal", "type": "boolean", "desc": "
The value will be true if decoding errors result in a TypeError being\nthrown.
" }, { "textRaw": "Type: {boolean}", "name": "ignoreBOM", "type": "boolean", "desc": "
The value will be true if the decoding result will include the byte order\nmark.
" } ] }, { "textRaw": "Class: `util.TextEncoder`", "name": "util.TextEncoder", "type": "class", "meta": { "added": [ "v8.3.0" ], "changes": [ { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/22281", "description": "The class is now available on the global object." } ] }, "desc": "
An implementation of the WHATWG Encoding Standard TextEncoder API. All\ninstances of TextEncoder only support UTF-8 encoding.
\n
const encoder = new TextEncoder();\nconst uint8array = encoder.encode('this is some data');\n\n
The TextEncoder class is also available on the global object.
", "methods": [ { "textRaw": "`textEncoder.encode([input])`", "name": "encode", "type": "method", "signatures": [ { "params": [ { "textRaw": "`input` {string} The text to encode. **Default:** an empty string.", "name": "input", "type": "string", "default": "an empty string", "desc": "The text to encode.", "optional": true } ], "return": { "textRaw": "Returns: {Uint8Array}", "name": "return", "type": "Uint8Array" } } ], "desc": "
UTF-8 encodes the input string and returns a Uint8Array containing the\nencoded bytes.
" }, { "textRaw": "`textEncoder.encodeInto(src, dest)`", "name": "encodeInto", "type": "method", "meta": { "added": [ "v12.11.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`src` {string} The text to encode.", "name": "src", "type": "string", "desc": "The text to encode." }, { "textRaw": "`dest` {Uint8Array} The array to hold the encode result.", "name": "dest", "type": "Uint8Array", "desc": "The array to hold the encode result." } ], "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object", "options": [ { "textRaw": "`read` {number} The read Unicode code units of src.", "name": "read", "type": "number", "desc": "The read Unicode code units of src." }, { "textRaw": "`written` {number} The written UTF-8 bytes of dest.", "name": "written", "type": "number", "desc": "The written UTF-8 bytes of dest." } ] } } ], "desc": "
UTF-8 encodes the src string to the dest Uint8Array and returns an object\ncontaining the read Unicode code units and written UTF-8 bytes.
\n
const encoder = new TextEncoder();\nconst src = 'this is some data';\nconst dest = new Uint8Array(10);\nconst { read, written } = encoder.encodeInto(src, dest);\n" } ], "properties": [ { "textRaw": "Type: {string}", "name": "encoding", "type": "string", "desc": "
The encoding supported by the TextEncoder instance. Always set to 'utf-8'.
" } ] } ], "properties": [ { "textRaw": "`util.types`", "name": "types", "type": "property", "meta": { "added": [ "v10.0.0" ], "changes": [ { "version": "v15.3.0", "pr-url": "https://github.com/nodejs/node/pull/34055", "description": "Exposed as `require('util/types')`." } ] }, "desc": "
util.types provides type checks for different kinds of built-in objects.\nUnlike instanceof or Object.prototype.toString.call(value), these checks do\nnot inspect properties of the object that are accessible from JavaScript (like\ntheir prototype), and usually have the overhead of calling into C++.
\n
The result generally does not make any guarantees about what kinds of\nproperties or behavior a value exposes in JavaScript. They are primarily\nuseful for addon developers who prefer to do type checking in JavaScript.
\n
The API is accessible via require('node:util').types or require('node:util/types').
", "methods": [ { "textRaw": "`util.types.isAnyArrayBuffer(value)`", "name": "isAnyArrayBuffer", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a built-in <ArrayBuffer> or\n<SharedArrayBuffer> instance.
\n
See also util.types.isArrayBuffer() and\nutil.types.isSharedArrayBuffer().
\n
util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true\nutil.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true\n" }, { "textRaw": "`util.types.isArrayBufferView(value)`", "name": "isArrayBufferView", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is an instance of one of the <ArrayBuffer>\nviews, such as typed array objects or <DataView>. Equivalent to ArrayBuffer.isView().
\n
util.types.isArrayBufferView(new Int8Array()); // true\nutil.types.isArrayBufferView(Buffer.from('hello world')); // true\nutil.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true\nutil.types.isArrayBufferView(new ArrayBuffer()); // false\n" }, { "textRaw": "`util.types.isArgumentsObject(value)`", "name": "isArgumentsObject", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is an arguments object.
\n
function foo() {\n util.types.isArgumentsObject(arguments); // Returns true\n}\n" }, { "textRaw": "`util.types.isArrayBuffer(value)`", "name": "isArrayBuffer", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a built-in <ArrayBuffer> instance.\nThis does not include <SharedArrayBuffer> instances. Usually, it is\ndesirable to test for both; See util.types.isAnyArrayBuffer() for that.
\n
util.types.isArrayBuffer(new ArrayBuffer()); // Returns true\nutil.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false\n" }, { "textRaw": "`util.types.isAsyncFunction(value)`", "name": "isAsyncFunction", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is an async function.\nThis only reports back what the JavaScript engine is seeing;\nin particular, the return value may not match the original source code if\na transpilation tool was used.
\n
util.types.isAsyncFunction(function foo() {}); // Returns false\nutil.types.isAsyncFunction(async function foo() {}); // Returns true\n" }, { "textRaw": "`util.types.isBigInt64Array(value)`", "name": "isBigInt64Array", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a BigInt64Array instance.
\n
util.types.isBigInt64Array(new BigInt64Array()); // Returns true\nutil.types.isBigInt64Array(new BigUint64Array()); // Returns false\n" }, { "textRaw": "`util.types.isBigIntObject(value)`", "name": "isBigIntObject", "type": "method", "meta": { "added": [ "v10.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a BigInt object, e.g. created\nby Object(BigInt(123)).
\n
util.types.isBigIntObject(Object(BigInt(123))); // Returns true\nutil.types.isBigIntObject(BigInt(123)); // Returns false\nutil.types.isBigIntObject(123); // Returns false\n" }, { "textRaw": "`util.types.isBigUint64Array(value)`", "name": "isBigUint64Array", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a BigUint64Array instance.
\n
util.types.isBigUint64Array(new BigInt64Array()); // Returns false\nutil.types.isBigUint64Array(new BigUint64Array()); // Returns true\n" }, { "textRaw": "`util.types.isBooleanObject(value)`", "name": "isBooleanObject", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a boolean object, e.g. created\nby new Boolean().
\n
util.types.isBooleanObject(false); // Returns false\nutil.types.isBooleanObject(true); // Returns false\nutil.types.isBooleanObject(new Boolean(false)); // Returns true\nutil.types.isBooleanObject(new Boolean(true)); // Returns true\nutil.types.isBooleanObject(Boolean(false)); // Returns false\nutil.types.isBooleanObject(Boolean(true)); // Returns false\n" }, { "textRaw": "`util.types.isBoxedPrimitive(value)`", "name": "isBoxedPrimitive", "type": "method", "meta": { "added": [ "v10.11.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is any boxed primitive object, e.g. created\nby new Boolean(), new String() or Object(Symbol()).
\n
For example:
\n
util.types.isBoxedPrimitive(false); // Returns false\nutil.types.isBoxedPrimitive(new Boolean(false)); // Returns true\nutil.types.isBoxedPrimitive(Symbol('foo')); // Returns false\nutil.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true\nutil.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true\n" }, { "textRaw": "`util.types.isCryptoKey(value)`", "name": "isCryptoKey", "type": "method", "meta": { "added": [ "v16.2.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {Object}", "name": "value", "type": "Object" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if value is a <CryptoKey>, false otherwise.
" }, { "textRaw": "`util.types.isDataView(value)`", "name": "isDataView", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a built-in <DataView> instance.
\n
const ab = new ArrayBuffer(20);\nutil.types.isDataView(new DataView(ab)); // Returns true\nutil.types.isDataView(new Float64Array()); // Returns false\n\n
See also ArrayBuffer.isView().
" }, { "textRaw": "`util.types.isDate(value)`", "name": "isDate", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a built-in <Date> instance.
\n
util.types.isDate(new Date()); // Returns true\n" }, { "textRaw": "`util.types.isExternal(value)`", "name": "isExternal", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a native External value.
\n
A native External value is a special type of object that contains a\nraw C++ pointer (void*) for access from native code, and has no other\nproperties. Such objects are created either by Node.js internals or native\naddons. In JavaScript, they are frozen objects with a\nnull prototype.
\n
#include <js_native_api.h>\n#include <stdlib.h>\nnapi_value result;\nstatic napi_value MyNapi(napi_env env, napi_callback_info info) {\n int* raw = (int*) malloc(1024);\n napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result);\n if (status != napi_ok) {\n napi_throw_error(env, NULL, \"napi_create_external failed\");\n return NULL;\n }\n return result;\n}\n...\nDECLARE_NAPI_PROPERTY(\"myNapi\", MyNapi)\n...\n\n
import native from 'napi_addon.node';\nimport { types } from 'node:util';\n\nconst data = native.myNapi();\ntypes.isExternal(data); // returns true\ntypes.isExternal(0); // returns false\ntypes.isExternal(new String('foo')); // returns false\n\n
const native = require('napi_addon.node');\nconst { types } = require('node:util');\n\nconst data = native.myNapi();\ntypes.isExternal(data); // returns true\ntypes.isExternal(0); // returns false\ntypes.isExternal(new String('foo')); // returns false\n\n
For further information on napi_create_external, refer to\nnapi_create_external().
" }, { "textRaw": "`util.types.isFloat16Array(value)`", "name": "isFloat16Array", "type": "method", "meta": { "added": [ "v24.0.0", "v22.16.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a built-in <Float16Array> instance.
\n
util.types.isFloat16Array(new ArrayBuffer()); // Returns false\nutil.types.isFloat16Array(new Float16Array()); // Returns true\nutil.types.isFloat16Array(new Float32Array()); // Returns false\n" }, { "textRaw": "`util.types.isFloat32Array(value)`", "name": "isFloat32Array", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a built-in <Float32Array> instance.
\n
util.types.isFloat32Array(new ArrayBuffer()); // Returns false\nutil.types.isFloat32Array(new Float32Array()); // Returns true\nutil.types.isFloat32Array(new Float64Array()); // Returns false\n" }, { "textRaw": "`util.types.isFloat64Array(value)`", "name": "isFloat64Array", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a built-in <Float64Array> instance.
\n
util.types.isFloat64Array(new ArrayBuffer()); // Returns false\nutil.types.isFloat64Array(new Uint8Array()); // Returns false\nutil.types.isFloat64Array(new Float64Array()); // Returns true\n" }, { "textRaw": "`util.types.isGeneratorFunction(value)`", "name": "isGeneratorFunction", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a generator function.\nThis only reports back what the JavaScript engine is seeing;\nin particular, the return value may not match the original source code if\na transpilation tool was used.
\n
util.types.isGeneratorFunction(function foo() {}); // Returns false\nutil.types.isGeneratorFunction(function* foo() {}); // Returns true\n" }, { "textRaw": "`util.types.isGeneratorObject(value)`", "name": "isGeneratorObject", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a generator object as returned from a\nbuilt-in generator function.\nThis only reports back what the JavaScript engine is seeing;\nin particular, the return value may not match the original source code if\na transpilation tool was used.
\n
function* foo() {}\nconst generator = foo();\nutil.types.isGeneratorObject(generator); // Returns true\n" }, { "textRaw": "`util.types.isInt8Array(value)`", "name": "isInt8Array", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a built-in <Int8Array> instance.
\n
util.types.isInt8Array(new ArrayBuffer()); // Returns false\nutil.types.isInt8Array(new Int8Array()); // Returns true\nutil.types.isInt8Array(new Float64Array()); // Returns false\n" }, { "textRaw": "`util.types.isInt16Array(value)`", "name": "isInt16Array", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a built-in <Int16Array> instance.
\n
util.types.isInt16Array(new ArrayBuffer()); // Returns false\nutil.types.isInt16Array(new Int16Array()); // Returns true\nutil.types.isInt16Array(new Float64Array()); // Returns false\n" }, { "textRaw": "`util.types.isInt32Array(value)`", "name": "isInt32Array", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a built-in <Int32Array> instance.
\n
util.types.isInt32Array(new ArrayBuffer()); // Returns false\nutil.types.isInt32Array(new Int32Array()); // Returns true\nutil.types.isInt32Array(new Float64Array()); // Returns false\n" }, { "textRaw": "`util.types.isKeyObject(value)`", "name": "isKeyObject", "type": "method", "meta": { "added": [ "v16.2.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {Object}", "name": "value", "type": "Object" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if value is a <KeyObject>, false otherwise.
" }, { "textRaw": "`util.types.isMap(value)`", "name": "isMap", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a built-in <Map> instance.
\n
util.types.isMap(new Map()); // Returns true\n" }, { "textRaw": "`util.types.isMapIterator(value)`", "name": "isMapIterator", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is an iterator returned for a built-in\n<Map> instance.
\n
const map = new Map();\nutil.types.isMapIterator(map.keys()); // Returns true\nutil.types.isMapIterator(map.values()); // Returns true\nutil.types.isMapIterator(map.entries()); // Returns true\nutil.types.isMapIterator(map[Symbol.iterator]()); // Returns true\n" }, { "textRaw": "`util.types.isModuleNamespaceObject(value)`", "name": "isModuleNamespaceObject", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is an instance of a Module Namespace Object.
\n
import * as ns from './a.js';\n\nutil.types.isModuleNamespaceObject(ns); // Returns true\n" }, { "textRaw": "`util.types.isNativeError(value)`", "name": "isNativeError", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [], "deprecated": [ "v24.2.0" ] }, "stability": 0, "stabilityText": "Deprecated: Use `Error.isError` instead.", "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Note: As of Node.js 24, Error.isError() is currently slower than util.types.isNativeError().\nIf performance is critical, consider benchmarking both in your environment.
\n
Returns true if the value was returned by the constructor of a\nbuilt-in Error type.
\n
console.log(util.types.isNativeError(new Error())); // true\nconsole.log(util.types.isNativeError(new TypeError())); // true\nconsole.log(util.types.isNativeError(new RangeError())); // true\n\n
Subclasses of the native error types are also native errors:
\n
class MyError extends Error {}\nconsole.log(util.types.isNativeError(new MyError())); // true\n\n
A value being instanceof a native error class is not equivalent to isNativeError()\nreturning true for that value. isNativeError() returns true for errors\nwhich come from a different realm while instanceof Error returns false\nfor these errors:
\n
import { createContext, runInContext } from 'node:vm';\nimport { types } from 'node:util';\n\nconst context = createContext({});\nconst myError = runInContext('new Error()', context);\nconsole.log(types.isNativeError(myError)); // true\nconsole.log(myError instanceof Error); // false\n\n
const { createContext, runInContext } = require('node:vm');\nconst { types } = require('node:util');\n\nconst context = createContext({});\nconst myError = runInContext('new Error()', context);\nconsole.log(types.isNativeError(myError)); // true\nconsole.log(myError instanceof Error); // false\n\n
Conversely, isNativeError() returns false for all objects which were not\nreturned by the constructor of a native error. That includes values\nwhich are instanceof native errors:
\n
const myError = { __proto__: Error.prototype };\nconsole.log(util.types.isNativeError(myError)); // false\nconsole.log(myError instanceof Error); // true\n" }, { "textRaw": "`util.types.isNumberObject(value)`", "name": "isNumberObject", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a number object, e.g. created\nby new Number().
\n
util.types.isNumberObject(0); // Returns false\nutil.types.isNumberObject(new Number(0)); // Returns true\n" }, { "textRaw": "`util.types.isPromise(value)`", "name": "isPromise", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a built-in <Promise>.
\n
util.types.isPromise(Promise.resolve(42)); // Returns true\n" }, { "textRaw": "`util.types.isProxy(value)`", "name": "isProxy", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a <Proxy> instance.
\n
const target = {};\nconst proxy = new Proxy(target, {});\nutil.types.isProxy(target); // Returns false\nutil.types.isProxy(proxy); // Returns true\n" }, { "textRaw": "`util.types.isRegExp(value)`", "name": "isRegExp", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a regular expression object.
\n
util.types.isRegExp(/abc/); // Returns true\nutil.types.isRegExp(new RegExp('abc')); // Returns true\n" }, { "textRaw": "`util.types.isSet(value)`", "name": "isSet", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a built-in <Set> instance.
\n
util.types.isSet(new Set()); // Returns true\n" }, { "textRaw": "`util.types.isSetIterator(value)`", "name": "isSetIterator", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is an iterator returned for a built-in\n<Set> instance.
\n
const set = new Set();\nutil.types.isSetIterator(set.keys()); // Returns true\nutil.types.isSetIterator(set.values()); // Returns true\nutil.types.isSetIterator(set.entries()); // Returns true\nutil.types.isSetIterator(set[Symbol.iterator]()); // Returns true\n" }, { "textRaw": "`util.types.isSharedArrayBuffer(value)`", "name": "isSharedArrayBuffer", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a built-in <SharedArrayBuffer> instance.\nThis does not include <ArrayBuffer> instances. Usually, it is\ndesirable to test for both; See util.types.isAnyArrayBuffer() for that.
\n
util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false\nutil.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true\n" }, { "textRaw": "`util.types.isStringObject(value)`", "name": "isStringObject", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a string object, e.g. created\nby new String().
\n
util.types.isStringObject('foo'); // Returns false\nutil.types.isStringObject(new String('foo')); // Returns true\n" }, { "textRaw": "`util.types.isSymbolObject(value)`", "name": "isSymbolObject", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a symbol object, created\nby calling Object() on a Symbol primitive.
\n
const symbol = Symbol('foo');\nutil.types.isSymbolObject(symbol); // Returns false\nutil.types.isSymbolObject(Object(symbol)); // Returns true\n" }, { "textRaw": "`util.types.isTypedArray(value)`", "name": "isTypedArray", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a built-in <TypedArray> instance.
\n
util.types.isTypedArray(new ArrayBuffer()); // Returns false\nutil.types.isTypedArray(new Uint8Array()); // Returns true\nutil.types.isTypedArray(new Float64Array()); // Returns true\n\n
See also ArrayBuffer.isView().
" }, { "textRaw": "`util.types.isUint8Array(value)`", "name": "isUint8Array", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a built-in <Uint8Array> instance.
\n
util.types.isUint8Array(new ArrayBuffer()); // Returns false\nutil.types.isUint8Array(new Uint8Array()); // Returns true\nutil.types.isUint8Array(new Float64Array()); // Returns false\n" }, { "textRaw": "`util.types.isUint8ClampedArray(value)`", "name": "isUint8ClampedArray", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a built-in <Uint8ClampedArray> instance.
\n
util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false\nutil.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true\nutil.types.isUint8ClampedArray(new Float64Array()); // Returns false\n" }, { "textRaw": "`util.types.isUint16Array(value)`", "name": "isUint16Array", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a built-in <Uint16Array> instance.
\n
util.types.isUint16Array(new ArrayBuffer()); // Returns false\nutil.types.isUint16Array(new Uint16Array()); // Returns true\nutil.types.isUint16Array(new Float64Array()); // Returns false\n" }, { "textRaw": "`util.types.isUint32Array(value)`", "name": "isUint32Array", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a built-in <Uint32Array> instance.
\n
util.types.isUint32Array(new ArrayBuffer()); // Returns false\nutil.types.isUint32Array(new Uint32Array()); // Returns true\nutil.types.isUint32Array(new Float64Array()); // Returns false\n" }, { "textRaw": "`util.types.isWeakMap(value)`", "name": "isWeakMap", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a built-in <WeakMap> instance.
\n
util.types.isWeakMap(new WeakMap()); // Returns true\n" }, { "textRaw": "`util.types.isWeakSet(value)`", "name": "isWeakSet", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Returns true if the value is a built-in <WeakSet> instance.
\n
util.types.isWeakSet(new WeakSet()); // Returns true\n" } ] } ], "modules": [ { "textRaw": "Deprecated APIs", "name": "deprecated_apis", "type": "module", "desc": "
The following APIs are deprecated and should no longer be used. Existing\napplications and modules should be updated to find alternative approaches.
", "methods": [ { "textRaw": "`util._extend(target, source)`", "name": "_extend", "type": "method", "meta": { "added": [ "v0.7.5" ], "changes": [], "deprecated": [ "v6.0.0" ] }, "stability": 0, "stabilityText": "Deprecated: Use `Object.assign()` instead.", "signatures": [ { "params": [ { "textRaw": "`target` {Object}", "name": "target", "type": "Object" }, { "textRaw": "`source` {Object}", "name": "source", "type": "Object" } ] } ], "desc": "
The util._extend() method was never intended to be used outside of internal\nNode.js modules. The community found and used it anyway.
\n
It is deprecated and should not be used in new code. JavaScript comes with very\nsimilar built-in functionality through Object.assign().
\n
An automated migration is available (source):
\n
npx codemod@latest @nodejs/util-extend-to-object-assign\n" }, { "textRaw": "`util.isArray(object)`", "name": "isArray", "type": "method", "meta": { "added": [ "v0.6.0" ], "changes": [], "deprecated": [ "v4.0.0" ] }, "stability": 0, "stabilityText": "Deprecated: Use `Array.isArray()` instead.", "signatures": [ { "params": [ { "textRaw": "`object` {any}", "name": "object", "type": "any" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "
Alias for Array.isArray().
\n
Returns true if the given object is an Array. Otherwise, returns false.
\n
const util = require('node:util');\n\nutil.isArray([]);\n// Returns: true\nutil.isArray(new Array());\n// Returns: true\nutil.isArray({});\n// Returns: false\n\n
An automated migration is available (source):
\n
npx codemod@latest @nodejs/util-is\n" } ], "displayName": "Deprecated APIs" } ], "displayName": "Util" } ] }