@@ -10,7 +10,11 @@ The `node:util` module supports the needs of Node.js internal APIs. Many of the
10
10
utilities are useful for application and module developers as well. To access
11
11
it:
12
12
13
- ``` js
13
+ ``` mjs
14
+ import util from ' node:util' ;
15
+ ```
16
+
17
+ ``` cjs
14
18
const util = require (' node:util' );
15
19
```
16
20
@@ -29,13 +33,27 @@ an `(err, value) => ...` callback as the last argument. In the callback, the
29
33
first argument will be the rejection reason (or ` null ` if the ` Promise `
30
34
resolved), and the second argument will be the resolved value.
31
35
32
- ``` js
33
- const util = require ( ' node:util' ) ;
36
+ ``` mjs
37
+ import { callbackify } from ' node:util' ;
34
38
35
39
async function fn () {
36
40
return ' hello world' ;
37
41
}
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);
39
57
40
58
callbackFunction ((err , ret ) => {
41
59
if (err) throw err;
@@ -89,11 +107,18 @@ environment variable. If the `section` name appears within the value of that
89
107
environment variable, then the returned function operates similar to
90
108
[ ` console.error() ` ] [ ] . If not, then the returned function is a no-op.
91
109
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' );
95
120
96
- debuglog (' hello from foo [%d]' , 123 );
121
+ log (' hello from foo [%d]' , 123 );
97
122
```
98
123
99
124
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.
108
133
109
134
The ` section ` supports wildcard also:
110
135
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' );
114
139
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 );
116
148
```
117
149
118
150
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
129
161
with a different function that doesn't have any initialization or
130
162
unnecessary wrapping.
131
163
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 ) => {
135
167
// Replace with a logging function that optimizes out
136
168
// 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;
138
179
});
139
180
```
140
181
@@ -152,9 +193,17 @@ If the `section` name appears within the value of that environment variable,
152
193
then the returned value will be ` true ` . If not, then the returned value will be
153
194
` false ` .
154
195
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 ;
158
207
if (enabled) {
159
208
console .log (' hello from foo [%d]' , 123 );
160
209
}
@@ -196,10 +245,18 @@ changes:
196
245
The ` util.deprecate() ` method wraps ` fn ` (which may be a function or class) in
197
246
such a way that it is marked as deprecated.
198
247
199
- ``` js
200
- const util = require ( ' node:util' ) ;
248
+ ``` mjs
249
+ import { deprecate } from ' node:util' ;
201
250
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 (() => {
203
260
// Do something here.
204
261
}, ' obsoleteFunction() is deprecated. Use newShinyFunction() instead.' );
205
262
```
@@ -213,11 +270,40 @@ emitting a warning.
213
270
If the same optional ` code ` is supplied in multiple calls to ` util.deprecate() ` ,
214
271
the warning will be emitted only once for that ` code ` .
215
272
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
+ ```
218
289
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
+ );
221
307
fn1 (); // Emits a deprecation warning with code DEP0001
222
308
fn2 (); // Does not emit a deprecation warning because it has the same code
223
309
```
@@ -398,19 +484,56 @@ changes:
398
484
Returns an array of call site objects containing the stack of
399
485
the caller function.
400
486
401
- ``` js
402
- const util = require ( ' node:util' ) ;
487
+ ``` mjs
488
+ import { getCallSites } from ' node:util' ;
403
489
404
490
function exampleFunction () {
405
- const callSites = util . getCallSites ();
491
+ const callSites = getCallSites ();
406
492
407
493
console .log (' Call Sites:' );
408
494
callSites .forEach ((callSite , index ) => {
409
495
console .log (` CallSite ${ index + 1 } :` );
410
496
console .log (` Function Name: ${ callSite .functionName } ` );
411
497
console .log (` Script Name: ${ callSite .scriptName } ` );
412
498
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 } ` );
414
537
});
415
538
// CallSite 1:
416
539
// Function Name: exampleFunction
@@ -441,13 +564,31 @@ When the `--enable-source-maps` flag is enabled, for example when using `--exper
441
564
` sourceMap ` will be true by default.
442
565
443
566
``` ts
444
- import util from ' node:util' ;
567
+ import { getCallSites } from ' node:util' ;
445
568
446
569
interface Foo {
447
570
foo: string ;
448
571
}
449
572
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 });
451
592
452
593
// With sourceMap:
453
594
// Function Name: ''
@@ -579,7 +720,24 @@ stream.write('It works!'); // Received data: "It works!"
579
720
580
721
ES6 example using ` class ` and ` extends ` :
581
722
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
583
741
const EventEmitter = require (' node:events' );
584
742
585
743
class MyStream extends EventEmitter {
@@ -762,7 +920,23 @@ util.inspect(baz); // '[foo] {}'
762
920
763
921
Circular references point to their anchor by using a reference index:
764
922
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
766
940
const { inspect } = require (' node:util' );
767
941
768
942
const obj = {};
@@ -780,16 +954,72 @@ console.log(inspect(obj));
780
954
781
955
The following example inspects all properties of the ` util ` object:
782
956
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
784
964
const util = require (' node:util' );
785
965
786
966
console .log (util .inspect (util, { showHidden: true , depth: null }));
787
967
```
788
968
789
969
The following example highlights the effect of the ` compact ` option:
790
970
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,\n consectetur adipiscing elit, sed do ' +
977
+ ' eiusmod \n tempor 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' );
793
1023
794
1024
const o = {
795
1025
a: [1 , 2 , [[
@@ -799,7 +1029,7 @@ const o = {
799
1029
' foo' ]], 4 ],
800
1030
b: new Map ([[' za' , 1 ], [' zb' , ' test' ]]),
801
1031
};
802
- console .log (util . inspect (o, { compact: true , depth: 5 , breakLength: 80 }));
1032
+ console .log (inspect (o, { compact: true , depth: 5 , breakLength: 80 }));
803
1033
804
1034
// { a:
805
1035
// [ 1,
@@ -811,7 +1041,7 @@ console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 }));
811
1041
// b: Map(2) { 'za' => 1, 'zb' => 'test' } }
812
1042
813
1043
// 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 }));
815
1045
816
1046
// {
817
1047
// a: [
@@ -844,7 +1074,18 @@ guarantee which entries are displayed. That means retrieving the same
844
1074
{WeakSet} entries twice may result in different output. Furthermore, entries
845
1075
with no remaining strong references may be garbage collected at any time.
846
1076
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
848
1089
const { inspect } = require (' node:util' );
849
1090
850
1091
const obj = { a: 1 };
@@ -858,7 +1099,32 @@ console.log(inspect(weakSet, { showHidden: true }));
858
1099
The ` sorted ` option ensures that an object's property insertion order does not
859
1100
impact the result of ` util.inspect() ` .
860
1101
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
862
1128
const { inspect } = require (' node:util' );
863
1129
const assert = require (' node:assert' );
864
1130
@@ -886,13 +1152,31 @@ assert.strict.equal(
886
1152
The ` numericSeparator ` option adds an underscore every three digits to all
887
1153
numbers.
888
1154
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
890
1174
const { inspect } = require (' node:util' );
891
1175
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 ;
896
1180
897
1181
console .log (inspect (thousand, { numericSeparator: true }));
898
1182
// 1_000
@@ -1018,15 +1302,46 @@ Objects may also define their own
1018
1302
which ` util.inspect() ` will invoke and use the result of when inspecting
1019
1303
the object.
1020
1304
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' );
1023
1338
1024
1339
class Box {
1025
1340
constructor (value ) {
1026
1341
this .value = value;
1027
1342
}
1028
1343
1029
- [util . inspect .custom ](depth , options , inspect ) {
1344
+ [inspect .custom ](depth , options , inspect ) {
1030
1345
if (depth < 0 ) {
1031
1346
return options .stylize (' [Box]' , ' special' );
1032
1347
}
@@ -1045,24 +1360,36 @@ class Box {
1045
1360
1046
1361
const box = new Box (true );
1047
1362
1048
- util . inspect (box);
1049
- // Returns: "Box< true >"
1363
+ console . log ( inspect (box) );
1364
+ // "Box< true >"
1050
1365
```
1051
1366
1052
1367
Custom ` [util.inspect.custom](depth, opts, inspect) ` functions typically return
1053
1368
a string but may return a value of any type that will be formatted accordingly
1054
1369
by ` util.inspect() ` .
1055
1370
1056
- ``` js
1057
- const util = require ( ' node:util' ) ;
1371
+ ``` mjs
1372
+ import { inspect } from ' node:util' ;
1058
1373
1059
1374
const obj = { foo: ' this will not show up in the inspect() output' };
1060
- obj[util . inspect .custom ] = (depth ) => {
1375
+ obj[inspect .custom ] = (depth ) => {
1061
1376
return { bar: ' baz' };
1062
1377
};
1063
1378
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' }"
1066
1393
```
1067
1394
1068
1395
### ` util.inspect.custom `
@@ -1122,12 +1449,21 @@ The `defaultOptions` value allows customization of the default options used by
1122
1449
object containing one or more valid [ ` util.inspect() ` ] [ ] options. Setting
1123
1450
option properties directly is also supported.
1124
1451
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 );
1128
1455
1129
1456
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 ;
1131
1467
console .log (arr); // logs the full array
1132
1468
```
1133
1469
@@ -1769,12 +2105,24 @@ Takes a function following the common error-first callback style, i.e. taking
1769
2105
an ` (err , value ) => ... ` callback as the last argument, and returns a version
1770
2106
that returns promises.
1771
2107
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' );
1775
2123
1776
- const stat = util . promisify (fs . stat );
1777
- stat (' .' ).then ((stats ) => {
2124
+ const promisifiedStat = promisify (stat);
2125
+ promisifiedStat (' .' ).then ((stats ) => {
1778
2126
// Do something with `stats`
1779
2127
}).catch ((error ) => {
1780
2128
// Handle the error.
@@ -1783,14 +2131,28 @@ stat('.').then((stats) => {
1783
2131
1784
2132
Or, equivalently using ` async function `s:
1785
2133
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' );
1789
2151
1790
- const stat = util. promisify(fs. stat);
2152
+ const promisifiedStat = promisify (stat);
1791
2153
1792
2154
async function callStat () {
1793
- const stats = await stat (' .' );
2155
+ const stats = await promisifiedStat (' .' );
1794
2156
console .log (` This directory is owned by ${ stats .uid } ` );
1795
2157
}
1796
2158
@@ -1809,8 +2171,8 @@ callback as its last argument.
1809
2171
Using ` promisify ()` on class methods or other methods that use ` this ` may not
1810
2172
work as expected unless handled specially:
1811
2173
1812
- ` ` ` js
1813
- const util = require ( ' node:util' ) ;
2174
+ ` ` ` mjs
2175
+ import { promisify } from ' node:util' ;
1814
2176
1815
2177
class Foo {
1816
2178
constructor () {
@@ -1824,8 +2186,33 @@ class Foo {
1824
2186
1825
2187
const foo = new Foo ();
1826
2188
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')
1829
2216
// naiveBar().then(a => console.log(a));
1830
2217
1831
2218
naiveBar .call (foo).then ((a ) => console .log (a)); // '42'
@@ -1839,19 +2226,35 @@ bindBar().then((a) => console.log(a)); // '42'
1839
2226
Using the ` util .promisify .custom ` symbol one can override the return value of
1840
2227
[` util .promisify ()` ][]:
1841
2228
1842
- ` ` ` js
1843
- const util = require ( ' node:util' ) ;
2229
+ ` ` ` mjs
2230
+ import { promisify } from ' node:util' ;
1844
2231
1845
2232
function doSomething (foo , callback ) {
1846
2233
// ...
1847
2234
}
1848
2235
1849
- doSomething[util . promisify .custom ] = (foo ) => {
2236
+ doSomething[promisify .custom ] = (foo ) => {
1850
2237
return getPromiseSomehow ();
1851
2238
};
1852
2239
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 ]);
1855
2258
// prints 'true'
1856
2259
` ` `
1857
2260
@@ -2594,12 +2997,24 @@ DECLARE_NAPI_PROPERTY("myNapi", MyNapi)
2594
2997
...
2595
2998
` ` `
2596
2999
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
2598
3011
const native = require (' napi_addon.node' );
3012
+ const { types } = require (' node:util' );
3013
+
2599
3014
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
2603
3018
` ` `
2604
3019
2605
3020
For further information on ` napi_create_external` , refer to
@@ -2823,11 +3238,23 @@ returning `true` for that value. `isNativeError()` returns `true` for errors
2823
3238
which come from a different [realm][] while ` instanceof Error ` returns ` false `
2824
3239
for these errors:
2825
3240
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
2831
3258
console .log (myError instanceof Error ); // false
2832
3259
` ` `
2833
3260
0 commit comments