Skip to content

Commit 7f48811

Browse files
mfdebianaduh95
authored andcommittedMar 9, 2025
doc: add esm examples to node:util
PR-URL: #56793 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
1 parent 20c032e commit 7f48811

File tree

1 file changed

+515
-88
lines changed

1 file changed

+515
-88
lines changed
 

‎doc/api/util.md

+515-88
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,11 @@ The `node:util` module supports the needs of Node.js internal APIs. Many of the
1010
utilities are useful for application and module developers as well. To access
1111
it:
1212

13-
```js
13+
```mjs
14+
import util from 'node:util';
15+
```
16+
17+
```cjs
1418
const util = require('node:util');
1519
```
1620

@@ -29,13 +33,27 @@ an `(err, value) => ...` callback as the last argument. In the callback, the
2933
first argument will be the rejection reason (or `null` if the `Promise`
3034
resolved), and the second argument will be the resolved value.
3135

32-
```js
33-
const util = require('node:util');
36+
```mjs
37+
import { callbackify } from 'node:util';
3438

3539
async function fn() {
3640
return 'hello world';
3741
}
38-
const callbackFunction = util.callbackify(fn);
42+
const callbackFunction = callbackify(fn);
43+
44+
callbackFunction((err, ret) => {
45+
if (err) throw err;
46+
console.log(ret);
47+
});
48+
```
49+
50+
```cjs
51+
const { callbackify } = require('node:util');
52+
53+
async function fn() {
54+
return 'hello world';
55+
}
56+
const callbackFunction = callbackify(fn);
3957

4058
callbackFunction((err, ret) => {
4159
if (err) throw err;
@@ -89,11 +107,18 @@ environment variable. If the `section` name appears within the value of that
89107
environment variable, then the returned function operates similar to
90108
[`console.error()`][]. If not, then the returned function is a no-op.
91109

92-
```js
93-
const util = require('node:util');
94-
const debuglog = util.debuglog('foo');
110+
```mjs
111+
import { debuglog } from 'node:util';
112+
const log = debuglog('foo');
113+
114+
log('hello from foo [%d]', 123);
115+
```
116+
117+
```cjs
118+
const { debuglog } = require('node:util');
119+
const log = debuglog('foo');
95120

96-
debuglog('hello from foo [%d]', 123);
121+
log('hello from foo [%d]', 123);
97122
```
98123

99124
If this program is run with `NODE_DEBUG=foo` in the environment, then
@@ -108,11 +133,18 @@ environment variable set, then it will not print anything.
108133

109134
The `section` supports wildcard also:
110135

111-
```js
112-
const util = require('node:util');
113-
const debuglog = util.debuglog('foo-bar');
136+
```mjs
137+
import { debuglog } from 'node:util';
138+
const log = debuglog('foo');
114139

115-
debuglog('hi there, it\'s foo-bar [%d]', 2333);
140+
log('hi there, it\'s foo-bar [%d]', 2333);
141+
```
142+
143+
```cjs
144+
const { debuglog } = require('node:util');
145+
const log = debuglog('foo');
146+
147+
log('hi there, it\'s foo-bar [%d]', 2333);
116148
```
117149

118150
if it is run with `NODE_DEBUG=foo*` in the environment, then it will output
@@ -129,12 +161,21 @@ The optional `callback` argument can be used to replace the logging function
129161
with a different function that doesn't have any initialization or
130162
unnecessary wrapping.
131163

132-
```js
133-
const util = require('node:util');
134-
let debuglog = util.debuglog('internals', (debug) => {
164+
```mjs
165+
import { debuglog } from 'node:util';
166+
let log = debuglog('internals', (debug) => {
135167
// Replace with a logging function that optimizes out
136168
// testing if the section is enabled
137-
debuglog = debug;
169+
log = debug;
170+
});
171+
```
172+
173+
```cjs
174+
const { debuglog } = require('node:util');
175+
let log = debuglog('internals', (debug) => {
176+
// Replace with a logging function that optimizes out
177+
// testing if the section is enabled
178+
log = debug;
138179
});
139180
```
140181

@@ -152,9 +193,17 @@ If the `section` name appears within the value of that environment variable,
152193
then the returned value will be `true`. If not, then the returned value will be
153194
`false`.
154195

155-
```js
156-
const util = require('node:util');
157-
const enabled = util.debuglog('foo').enabled;
196+
```mjs
197+
import { debuglog } from 'node:util';
198+
const enabled = debuglog('foo').enabled;
199+
if (enabled) {
200+
console.log('hello from foo [%d]', 123);
201+
}
202+
```
203+
204+
```cjs
205+
const { debuglog } = require('node:util');
206+
const enabled = debuglog('foo').enabled;
158207
if (enabled) {
159208
console.log('hello from foo [%d]', 123);
160209
}
@@ -196,10 +245,18 @@ changes:
196245
The `util.deprecate()` method wraps `fn` (which may be a function or class) in
197246
such a way that it is marked as deprecated.
198247

199-
```js
200-
const util = require('node:util');
248+
```mjs
249+
import { deprecate } from 'node:util';
201250

202-
exports.obsoleteFunction = util.deprecate(() => {
251+
export const obsoleteFunction = deprecate(() => {
252+
// Do something here.
253+
}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');
254+
```
255+
256+
```cjs
257+
const { deprecate } = require('node:util');
258+
259+
exports.obsoleteFunction = deprecate(() => {
203260
// Do something here.
204261
}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');
205262
```
@@ -213,11 +270,40 @@ emitting a warning.
213270
If the same optional `code` is supplied in multiple calls to `util.deprecate()`,
214271
the warning will be emitted only once for that `code`.
215272

216-
```js
217-
const util = require('node:util');
273+
```mjs
274+
import { deprecate } from 'node:util';
275+
276+
const fn1 = deprecate(
277+
() => 'a value',
278+
'deprecation message',
279+
'DEP0001',
280+
);
281+
const fn2 = deprecate(
282+
() => 'a different value',
283+
'other dep message',
284+
'DEP0001',
285+
);
286+
fn1(); // Emits a deprecation warning with code DEP0001
287+
fn2(); // Does not emit a deprecation warning because it has the same code
288+
```
218289

219-
const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001');
220-
const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001');
290+
```cjs
291+
const { deprecate } = require('node:util');
292+
293+
const fn1 = deprecate(
294+
function() {
295+
return 'a value';
296+
},
297+
'deprecation message',
298+
'DEP0001',
299+
);
300+
const fn2 = deprecate(
301+
function() {
302+
return 'a different value';
303+
},
304+
'other dep message',
305+
'DEP0001',
306+
);
221307
fn1(); // Emits a deprecation warning with code DEP0001
222308
fn2(); // Does not emit a deprecation warning because it has the same code
223309
```
@@ -398,19 +484,56 @@ changes:
398484
Returns an array of call site objects containing the stack of
399485
the caller function.
400486

401-
```js
402-
const util = require('node:util');
487+
```mjs
488+
import { getCallSites } from 'node:util';
403489

404490
function exampleFunction() {
405-
const callSites = util.getCallSites();
491+
const callSites = getCallSites();
406492

407493
console.log('Call Sites:');
408494
callSites.forEach((callSite, index) => {
409495
console.log(`CallSite ${index + 1}:`);
410496
console.log(`Function Name: ${callSite.functionName}`);
411497
console.log(`Script Name: ${callSite.scriptName}`);
412498
console.log(`Line Number: ${callSite.lineNumber}`);
413-
console.log(`Column Number: ${callSite.columnNumber}`);
499+
console.log(`Column Number: ${callSite.column}`);
500+
});
501+
// CallSite 1:
502+
// Function Name: exampleFunction
503+
// Script Name: /home/example.js
504+
// Line Number: 5
505+
// Column Number: 26
506+
507+
// CallSite 2:
508+
// Function Name: anotherFunction
509+
// Script Name: /home/example.js
510+
// Line Number: 22
511+
// Column Number: 3
512+
513+
// ...
514+
}
515+
516+
// A function to simulate another stack layer
517+
function anotherFunction() {
518+
exampleFunction();
519+
}
520+
521+
anotherFunction();
522+
```
523+
524+
```cjs
525+
const { getCallSites } = require('node:util');
526+
527+
function exampleFunction() {
528+
const callSites = getCallSites();
529+
530+
console.log('Call Sites:');
531+
callSites.forEach((callSite, index) => {
532+
console.log(`CallSite ${index + 1}:`);
533+
console.log(`Function Name: ${callSite.functionName}`);
534+
console.log(`Script Name: ${callSite.scriptName}`);
535+
console.log(`Line Number: ${callSite.lineNumber}`);
536+
console.log(`Column Number: ${callSite.column}`);
414537
});
415538
// CallSite 1:
416539
// Function Name: exampleFunction
@@ -441,13 +564,31 @@ When the `--enable-source-maps` flag is enabled, for example when using `--exper
441564
`sourceMap` will be true by default.
442565

443566
```ts
444-
import util from 'node:util';
567+
import { getCallSites } from 'node:util';
445568

446569
interface Foo {
447570
foo: string;
448571
}
449572

450-
const callSites = util.getCallSites({ sourceMap: true });
573+
const callSites = getCallSites({ sourceMap: true });
574+
575+
// With sourceMap:
576+
// Function Name: ''
577+
// Script Name: example.js
578+
// Line Number: 7
579+
// Column Number: 26
580+
581+
// Without sourceMap:
582+
// Function Name: ''
583+
// Script Name: example.js
584+
// Line Number: 2
585+
// Column Number: 26
586+
```
587+
588+
```cjs
589+
const { getCallSites } = require('node:util');
590+
591+
const callSites = getCallSites({ sourceMap: true });
451592

452593
// With sourceMap:
453594
// Function Name: ''
@@ -579,7 +720,24 @@ stream.write('It works!'); // Received data: "It works!"
579720

580721
ES6 example using `class` and `extends`:
581722

582-
```js
723+
```mjs
724+
import EventEmitter from 'node:events';
725+
726+
class MyStream extends EventEmitter {
727+
write(data) {
728+
this.emit('data', data);
729+
}
730+
}
731+
732+
const stream = new MyStream();
733+
734+
stream.on('data', (data) => {
735+
console.log(`Received data: "${data}"`);
736+
});
737+
stream.write('With ES6');
738+
```
739+
740+
```cjs
583741
const EventEmitter = require('node:events');
584742

585743
class MyStream extends EventEmitter {
@@ -762,7 +920,23 @@ util.inspect(baz); // '[foo] {}'
762920

763921
Circular references point to their anchor by using a reference index:
764922

765-
```js
923+
```mjs
924+
import { inspect } from 'node:util';
925+
926+
const obj = {};
927+
obj.a = [obj];
928+
obj.b = {};
929+
obj.b.inner = obj.b;
930+
obj.b.obj = obj;
931+
932+
console.log(inspect(obj));
933+
// <ref *1> {
934+
// a: [ [Circular *1] ],
935+
// b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }
936+
// }
937+
```
938+
939+
```cjs
766940
const { inspect } = require('node:util');
767941

768942
const obj = {};
@@ -780,16 +954,72 @@ console.log(inspect(obj));
780954

781955
The following example inspects all properties of the `util` object:
782956

783-
```js
957+
```mjs
958+
import util from 'node:util';
959+
960+
console.log(util.inspect(util, { showHidden: true, depth: null }));
961+
```
962+
963+
```cjs
784964
const util = require('node:util');
785965

786966
console.log(util.inspect(util, { showHidden: true, depth: null }));
787967
```
788968

789969
The following example highlights the effect of the `compact` option:
790970

791-
```js
792-
const util = require('node:util');
971+
```mjs
972+
import { inspect } from 'node:util';
973+
974+
const o = {
975+
a: [1, 2, [[
976+
'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' +
977+
'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.',
978+
'test',
979+
'foo']], 4],
980+
b: new Map([['za', 1], ['zb', 'test']]),
981+
};
982+
console.log(inspect(o, { compact: true, depth: 5, breakLength: 80 }));
983+
984+
// { a:
985+
// [ 1,
986+
// 2,
987+
// [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line
988+
// 'test',
989+
// 'foo' ] ],
990+
// 4 ],
991+
// b: Map(2) { 'za' => 1, 'zb' => 'test' } }
992+
993+
// Setting `compact` to false or an integer creates more reader friendly output.
994+
console.log(inspect(o, { compact: false, depth: 5, breakLength: 80 }));
995+
996+
// {
997+
// a: [
998+
// 1,
999+
// 2,
1000+
// [
1001+
// [
1002+
// 'Lorem ipsum dolor sit amet,\n' +
1003+
// 'consectetur adipiscing elit, sed do eiusmod \n' +
1004+
// 'tempor incididunt ut labore et dolore magna aliqua.',
1005+
// 'test',
1006+
// 'foo'
1007+
// ]
1008+
// ],
1009+
// 4
1010+
// ],
1011+
// b: Map(2) {
1012+
// 'za' => 1,
1013+
// 'zb' => 'test'
1014+
// }
1015+
// }
1016+
1017+
// Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a
1018+
// single line.
1019+
```
1020+
1021+
```cjs
1022+
const { inspect } = require('node:util');
7931023

7941024
const o = {
7951025
a: [1, 2, [[
@@ -799,7 +1029,7 @@ const o = {
7991029
'foo']], 4],
8001030
b: new Map([['za', 1], ['zb', 'test']]),
8011031
};
802-
console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 }));
1032+
console.log(inspect(o, { compact: true, depth: 5, breakLength: 80 }));
8031033

8041034
// { a:
8051035
// [ 1,
@@ -811,7 +1041,7 @@ console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 }));
8111041
// b: Map(2) { 'za' => 1, 'zb' => 'test' } }
8121042

8131043
// Setting `compact` to false or an integer creates more reader friendly output.
814-
console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 }));
1044+
console.log(inspect(o, { compact: false, depth: 5, breakLength: 80 }));
8151045

8161046
// {
8171047
// a: [
@@ -844,7 +1074,18 @@ guarantee which entries are displayed. That means retrieving the same
8441074
{WeakSet} entries twice may result in different output. Furthermore, entries
8451075
with no remaining strong references may be garbage collected at any time.
8461076

847-
```js
1077+
```mjs
1078+
import { inspect } from 'node:util';
1079+
1080+
const obj = { a: 1 };
1081+
const obj2 = { b: 2 };
1082+
const weakSet = new WeakSet([obj, obj2]);
1083+
1084+
console.log(inspect(weakSet, { showHidden: true }));
1085+
// WeakSet { { a: 1 }, { b: 2 } }
1086+
```
1087+
1088+
```cjs
8481089
const { inspect } = require('node:util');
8491090

8501091
const obj = { a: 1 };
@@ -858,7 +1099,32 @@ console.log(inspect(weakSet, { showHidden: true }));
8581099
The `sorted` option ensures that an object's property insertion order does not
8591100
impact the result of `util.inspect()`.
8601101

861-
```js
1102+
```mjs
1103+
import { inspect } from 'node:util';
1104+
import assert from 'node:assert';
1105+
1106+
const o1 = {
1107+
b: [2, 3, 1],
1108+
a: '`a` comes before `b`',
1109+
c: new Set([2, 3, 1]),
1110+
};
1111+
console.log(inspect(o1, { sorted: true }));
1112+
// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } }
1113+
console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));
1114+
// { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }
1115+
1116+
const o2 = {
1117+
c: new Set([2, 1, 3]),
1118+
a: '`a` comes before `b`',
1119+
b: [2, 3, 1],
1120+
};
1121+
assert.strict.equal(
1122+
inspect(o1, { sorted: true }),
1123+
inspect(o2, { sorted: true }),
1124+
);
1125+
```
1126+
1127+
```cjs
8621128
const { inspect } = require('node:util');
8631129
const assert = require('node:assert');
8641130

@@ -886,13 +1152,31 @@ assert.strict.equal(
8861152
The `numericSeparator` option adds an underscore every three digits to all
8871153
numbers.
8881154

889-
```js
1155+
```mjs
1156+
import { inspect } from 'node:util';
1157+
1158+
const thousand = 1000;
1159+
const million = 1000000;
1160+
const bigNumber = 123456789n;
1161+
const bigDecimal = 1234.12345;
1162+
1163+
console.log(inspect(thousand, { numericSeparator: true }));
1164+
// 1_000
1165+
console.log(inspect(million, { numericSeparator: true }));
1166+
// 1_000_000
1167+
console.log(inspect(bigNumber, { numericSeparator: true }));
1168+
// 123_456_789n
1169+
console.log(inspect(bigDecimal, { numericSeparator: true }));
1170+
// 1_234.123_45
1171+
```
1172+
1173+
```cjs
8901174
const { inspect } = require('node:util');
8911175

892-
const thousand = 1_000;
893-
const million = 1_000_000;
894-
const bigNumber = 123_456_789n;
895-
const bigDecimal = 1_234.123_45;
1176+
const thousand = 1000;
1177+
const million = 1000000;
1178+
const bigNumber = 123456789n;
1179+
const bigDecimal = 1234.12345;
8961180

8971181
console.log(inspect(thousand, { numericSeparator: true }));
8981182
// 1_000
@@ -1018,15 +1302,46 @@ Objects may also define their own
10181302
which `util.inspect()` will invoke and use the result of when inspecting
10191303
the object.
10201304

1021-
```js
1022-
const util = require('node:util');
1305+
```mjs
1306+
import { inspect } from 'node:util';
1307+
1308+
class Box {
1309+
constructor(value) {
1310+
this.value = value;
1311+
}
1312+
1313+
[inspect.custom](depth, options, inspect) {
1314+
if (depth < 0) {
1315+
return options.stylize('[Box]', 'special');
1316+
}
1317+
1318+
const newOptions = Object.assign({}, options, {
1319+
depth: options.depth === null ? null : options.depth - 1,
1320+
});
1321+
1322+
// Five space padding because that's the size of "Box< ".
1323+
const padding = ' '.repeat(5);
1324+
const inner = inspect(this.value, newOptions)
1325+
.replace(/\n/g, `\n${padding}`);
1326+
return `${options.stylize('Box', 'special')}< ${inner} >`;
1327+
}
1328+
}
1329+
1330+
const box = new Box(true);
1331+
1332+
console.log(inspect(box));
1333+
// "Box< true >"
1334+
```
1335+
1336+
```cjs
1337+
const { inspect } = require('node:util');
10231338

10241339
class Box {
10251340
constructor(value) {
10261341
this.value = value;
10271342
}
10281343

1029-
[util.inspect.custom](depth, options, inspect) {
1344+
[inspect.custom](depth, options, inspect) {
10301345
if (depth < 0) {
10311346
return options.stylize('[Box]', 'special');
10321347
}
@@ -1045,24 +1360,36 @@ class Box {
10451360

10461361
const box = new Box(true);
10471362

1048-
util.inspect(box);
1049-
// Returns: "Box< true >"
1363+
console.log(inspect(box));
1364+
// "Box< true >"
10501365
```
10511366

10521367
Custom `[util.inspect.custom](depth, opts, inspect)` functions typically return
10531368
a string but may return a value of any type that will be formatted accordingly
10541369
by `util.inspect()`.
10551370

1056-
```js
1057-
const util = require('node:util');
1371+
```mjs
1372+
import { inspect } from 'node:util';
10581373

10591374
const obj = { foo: 'this will not show up in the inspect() output' };
1060-
obj[util.inspect.custom] = (depth) => {
1375+
obj[inspect.custom] = (depth) => {
10611376
return { bar: 'baz' };
10621377
};
10631378

1064-
util.inspect(obj);
1065-
// Returns: "{ bar: 'baz' }"
1379+
console.log(inspect(obj));
1380+
// "{ bar: 'baz' }"
1381+
```
1382+
1383+
```cjs
1384+
const { inspect } = require('node:util');
1385+
1386+
const obj = { foo: 'this will not show up in the inspect() output' };
1387+
obj[inspect.custom] = (depth) => {
1388+
return { bar: 'baz' };
1389+
};
1390+
1391+
console.log(inspect(obj));
1392+
// "{ bar: 'baz' }"
10661393
```
10671394

10681395
### `util.inspect.custom`
@@ -1122,12 +1449,21 @@ The `defaultOptions` value allows customization of the default options used by
11221449
object containing one or more valid [`util.inspect()`][] options. Setting
11231450
option properties directly is also supported.
11241451

1125-
```js
1126-
const util = require('node:util');
1127-
const arr = Array(101).fill(0);
1452+
```mjs
1453+
import { inspect } from 'node:util';
1454+
const arr = Array(156).fill(0);
11281455

11291456
console.log(arr); // Logs the truncated array
1130-
util.inspect.defaultOptions.maxArrayLength = null;
1457+
inspect.defaultOptions.maxArrayLength = null;
1458+
console.log(arr); // logs the full array
1459+
```
1460+
1461+
```cjs
1462+
const { inspect } = require('node:util');
1463+
const arr = Array(156).fill(0);
1464+
1465+
console.log(arr); // Logs the truncated array
1466+
inspect.defaultOptions.maxArrayLength = null;
11311467
console.log(arr); // logs the full array
11321468
```
11331469

@@ -1769,12 +2105,24 @@ Takes a function following the common error-first callback style, i.e. taking
17692105
an `(err, value) => ...` callback as the last argument, and returns a version
17702106
that returns promises.
17712107
1772-
```js
1773-
const util = require('node:util');
1774-
const fs = require('node:fs');
2108+
```mjs
2109+
import { promisify } from 'node:util';
2110+
import { stat } from 'node:fs';
2111+
2112+
const promisifiedStat = promisify(stat);
2113+
promisifiedStat('.').then((stats) => {
2114+
// Do something with `stats`
2115+
}).catch((error) => {
2116+
// Handle the error.
2117+
});
2118+
```
2119+
2120+
```cjs
2121+
const { promisify } = require('node:util');
2122+
const { stat } = require('node:fs');
17752123

1776-
const stat = util.promisify(fs.stat);
1777-
stat('.').then((stats) => {
2124+
const promisifiedStat = promisify(stat);
2125+
promisifiedStat('.').then((stats) => {
17782126
// Do something with `stats`
17792127
}).catch((error) => {
17802128
// Handle the error.
@@ -1783,14 +2131,28 @@ stat('.').then((stats) => {
17832131
17842132
Or, equivalently using `async function`s:
17852133

1786-
```js
1787-
const util = require('node:util');
1788-
const fs = require('node:fs');
2134+
```mjs
2135+
import { promisify } from 'node:util';
2136+
import { stat } from 'node:fs';
2137+
2138+
const promisifiedStat = promisify(stat);
2139+
2140+
async function callStat() {
2141+
const stats = await promisifiedStat('.');
2142+
console.log(`This directory is owned by ${stats.uid}`);
2143+
}
2144+
2145+
callStat();
2146+
```
2147+
2148+
```cjs
2149+
const { promisify } = require('node:util');
2150+
const { stat } = require('node:fs');
17892151

1790-
const stat = util.promisify(fs.stat);
2152+
const promisifiedStat = promisify(stat);
17912153

17922154
async function callStat() {
1793-
const stats = await stat('.');
2155+
const stats = await promisifiedStat('.');
17942156
console.log(`This directory is owned by ${stats.uid}`);
17952157
}
17962158

@@ -1809,8 +2171,8 @@ callback as its last argument.
18092171
Using `promisify()` on class methods or other methods that use `this` may not
18102172
work as expected unless handled specially:
18112173
1812-
```js
1813-
const util = require('node:util');
2174+
```mjs
2175+
import { promisify } from 'node:util';
18142176

18152177
class Foo {
18162178
constructor() {
@@ -1824,8 +2186,33 @@ class Foo {
18242186

18252187
const foo = new Foo();
18262188

1827-
const naiveBar = util.promisify(foo.bar);
1828-
// TypeError: Cannot read property 'a' of undefined
2189+
const naiveBar = promisify(foo.bar);
2190+
// TypeError: Cannot read properties of undefined (reading 'a')
2191+
// naiveBar().then(a => console.log(a));
2192+
2193+
naiveBar.call(foo).then((a) => console.log(a)); // '42'
2194+
2195+
const bindBar = naiveBar.bind(foo);
2196+
bindBar().then((a) => console.log(a)); // '42'
2197+
```
2198+
2199+
```cjs
2200+
const { promisify } = require('node:util');
2201+
2202+
class Foo {
2203+
constructor() {
2204+
this.a = 42;
2205+
}
2206+
2207+
bar(callback) {
2208+
callback(null, this.a);
2209+
}
2210+
}
2211+
2212+
const foo = new Foo();
2213+
2214+
const naiveBar = promisify(foo.bar);
2215+
// TypeError: Cannot read properties of undefined (reading 'a')
18292216
// naiveBar().then(a => console.log(a));
18302217

18312218
naiveBar.call(foo).then((a) => console.log(a)); // '42'
@@ -1839,19 +2226,35 @@ bindBar().then((a) => console.log(a)); // '42'
18392226
Using the `util.promisify.custom` symbol one can override the return value of
18402227
[`util.promisify()`][]:
18412228
1842-
```js
1843-
const util = require('node:util');
2229+
```mjs
2230+
import { promisify } from 'node:util';
18442231

18452232
function doSomething(foo, callback) {
18462233
// ...
18472234
}
18482235

1849-
doSomething[util.promisify.custom] = (foo) => {
2236+
doSomething[promisify.custom] = (foo) => {
18502237
return getPromiseSomehow();
18512238
};
18522239

1853-
const promisified = util.promisify(doSomething);
1854-
console.log(promisified === doSomething[util.promisify.custom]);
2240+
const promisified = promisify(doSomething);
2241+
console.log(promisified === doSomething[promisify.custom]);
2242+
// prints 'true'
2243+
```
2244+
2245+
```cjs
2246+
const { promisify } = require('node:util');
2247+
2248+
function doSomething(foo, callback) {
2249+
// ...
2250+
}
2251+
2252+
doSomething[promisify.custom] = (foo) => {
2253+
return getPromiseSomehow();
2254+
};
2255+
2256+
const promisified = promisify(doSomething);
2257+
console.log(promisified === doSomething[promisify.custom]);
18552258
// prints 'true'
18562259
```
18572260
@@ -2594,12 +2997,24 @@ DECLARE_NAPI_PROPERTY("myNapi", MyNapi)
25942997
...
25952998
```
25962999
2597-
```js
3000+
```mjs
3001+
import native from 'napi_addon.node';
3002+
import { types } from 'node:util';
3003+
3004+
const data = native.myNapi();
3005+
types.isExternal(data); // returns true
3006+
types.isExternal(0); // returns false
3007+
types.isExternal(new String('foo')); // returns false
3008+
```
3009+
3010+
```cjs
25983011
const native = require('napi_addon.node');
3012+
const { types } = require('node:util');
3013+
25993014
const data = native.myNapi();
2600-
util.types.isExternal(data); // returns true
2601-
util.types.isExternal(0); // returns false
2602-
util.types.isExternal(new String('foo')); // returns false
3015+
types.isExternal(data); // returns true
3016+
types.isExternal(0); // returns false
3017+
types.isExternal(new String('foo')); // returns false
26033018
```
26043019
26053020
For further information on `napi_create_external`, refer to
@@ -2823,11 +3238,23 @@ returning `true` for that value. `isNativeError()` returns `true` for errors
28233238
which come from a different [realm][] while `instanceof Error` returns `false`
28243239
for these errors:
28253240
2826-
```js
2827-
const vm = require('node:vm');
2828-
const context = vm.createContext({});
2829-
const myError = vm.runInContext('new Error()', context);
2830-
console.log(util.types.isNativeError(myError)); // true
3241+
```mjs
3242+
import { createContext, runInContext } from 'node:vm';
3243+
import { types } from 'node:util';
3244+
3245+
const context = createContext({});
3246+
const myError = runInContext('new Error()', context);
3247+
console.log(types.isNativeError(myError)); // true
3248+
console.log(myError instanceof Error); // false
3249+
```
3250+
3251+
```cjs
3252+
const { createContext, runInContext } = require('node:vm');
3253+
const { types } = require('node:util');
3254+
3255+
const context = createContext({});
3256+
const myError = runInContext('new Error()', context);
3257+
console.log(types.isNativeError(myError)); // true
28313258
console.log(myError instanceof Error); // false
28323259
```
28333260

0 commit comments

Comments
 (0)
Please sign in to comment.