-
-
Notifications
You must be signed in to change notification settings - Fork 35.6k
Expand file tree
/
Copy pathutil.md
More file actions
1023 lines (774 loc) Β· 24.5 KB
/
util.md
File metadata and controls
1023 lines (774 loc) Β· 24.5 KB
Edit and raw actions
OlderNewer
Β
1
# Util
2
3
> Stability: 2 - Stable
4
5
The `util` module is primarily designed to support the needs of Node.js' own
6
internal APIs. However, many of the utilities are useful for application and
7
module developers as well. It can be accessed using:
8
9
```js
10
const util = require('util');
11
```
12
13
## util.callbackify(original)
14
<!-- YAML
15
added: REPLACEME
16
-->
17
18
* `original` {Function} An `async` function
19
* Returns: {Function} a callback style function
20
21
Takes an `async` function (or a function that returns a Promise) and returns a
22
function following the Node.js error first callback style. In the callback, the
23
first argument will be the rejection reason (or `null` if the Promise resolved),
24
and the second argument will be the resolved value.
25
26
For example:
27
28
```js
29
const util = require('util');
30
31
async function fn() {
32
return await Promise.resolve('hello world');
33
}
34
const callbackFunction = util.callbackify(fn);
35
36
callbackFunction((err, ret) => {
37
if (err) throw err;
38
console.log(ret);
39
});
40
```
41
42
Will print:
43
44
```txt
45
hello world
46
```
47
48
*Note*:
49
50
* The callback is executed asynchronously, and will have a limited stack trace.
51
If the callback throws, the process will emit an [`'uncaughtException'`][]
52
event, and if not handled will exit.
53
54
* Since `null` has a special meaning as the first argument to a callback, if a
55
wrapped function rejects a `Promise` with a falsy value as a reason, the value
56
is wrapped in an `Error` with the original value stored in a field named
57
`reason`.
58
```js
59
function fn() {
60
return Promise.reject(null);
61
}
62
const callbackFunction = util.callbackify(fn);
63
64
callbackFunction((err, ret) => {
65
// When the Promise was rejected with `null` it is wrapped with an Error and
66
// the original value is stored in `reason`.
67
err && err.hasOwnProperty('reason') && err.reason === null; // true
68
});
69
```
70
71
## util.debuglog(section)
72
<!-- YAML
73
added: v0.11.3
74
-->
75
76
* `section` {string} A string identifying the portion of the application for
77
which the `debuglog` function is being created.
78
* Returns: {Function} The logging function
79
80
The `util.debuglog()` method is used to create a function that conditionally
81
writes debug messages to `stderr` based on the existence of the `NODE_DEBUG`
82
environment variable. If the `section` name appears within the value of that
83
environment variable, then the returned function operates similar to
84
[`console.error()`][]. If not, then the returned function is a no-op.
85
86
For example:
87
88
```js
89
const util = require('util');
90
const debuglog = util.debuglog('foo');
91
92
debuglog('hello from foo [%d]', 123);
93
```
94
95
If this program is run with `NODE_DEBUG=foo` in the environment, then
96
it will output something like:
97
98
```txt
99
FOO 3245: hello from foo [123]
100
```
101
102
where `3245` is the process id. If it is not run with that
103
environment variable set, then it will not print anything.
104
105
Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`
106
environment variable. For example: `NODE_DEBUG=fs,net,tls`.
107
108
## util.deprecate(function, string)
109
<!-- YAML
110
added: v0.8.0
111
-->
112
113
The `util.deprecate()` method wraps the given `function` or class in such a way that
114
it is marked as deprecated.
115
116
<!-- eslint-disable prefer-rest-params -->
117
```js
118
const util = require('util');
119
120
exports.puts = util.deprecate(function() {
121
for (let i = 0, len = arguments.length; i < len; ++i) {
122
process.stdout.write(arguments[i] + '\n');
123
}
124
}, 'util.puts: Use console.log instead');
125
```
126
127
When called, `util.deprecate()` will return a function that will emit a
128
`DeprecationWarning` using the `process.on('warning')` event. By default,
129
this warning will be emitted and printed to `stderr` exactly once, the first
130
time it is called. After the warning is emitted, the wrapped `function`
131
is called.
132
133
If either the `--no-deprecation` or `--no-warnings` command line flags are
134
used, or if the `process.noDeprecation` property is set to `true` *prior* to
135
the first deprecation warning, the `util.deprecate()` method does nothing.
136
137
If the `--trace-deprecation` or `--trace-warnings` command line flags are set,
138
or the `process.traceDeprecation` property is set to `true`, a warning and a
139
stack trace are printed to `stderr` the first time the deprecated function is
140
called.
141
142
If the `--throw-deprecation` command line flag is set, or the
143
`process.throwDeprecation` property is set to `true`, then an exception will be
144
thrown when the deprecated function is called.
145
146
The `--throw-deprecation` command line flag and `process.throwDeprecation`
147
property take precedence over `--trace-deprecation` and
148
`process.traceDeprecation`.
149
150
## util.format(format[, ...args])
151
<!-- YAML
152
added: v0.5.3
153
-->
154
155
* `format` {string} A `printf`-like format string.
156
157
The `util.format()` method returns a formatted string using the first argument
158
as a `printf`-like format.
159
160
The first argument is a string containing zero or more *placeholder* tokens.
161
Each placeholder token is replaced with the converted value from the
162
corresponding argument. Supported placeholders are:
163
164
* `%s` - String.
165
* `%d` - Number (integer or floating point value).
166
* `%i` - Integer.
167
* `%f` - Floating point value.
168
* `%j` - JSON. Replaced with the string `'[Circular]'` if the argument
169
contains circular references.
170
* `%%` - single percent sign (`'%'`). This does not consume an argument.
171
172
If the placeholder does not have a corresponding argument, the placeholder is
173
not replaced.
174
175
```js
176
util.format('%s:%s', 'foo');
177
// Returns: 'foo:%s'
178
```
179
180
If there are more arguments passed to the `util.format()` method than the
181
number of placeholders, the extra arguments are coerced into strings (for
182
objects and symbols, `util.inspect()` is used) then concatenated to the
183
returned string, each delimited by a space.
184
185
```js
186
util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'
187
```
188
189
If the first argument is not a format string then `util.format()` returns
190
a string that is the concatenation of all arguments separated by spaces.
191
Each argument is converted to a string using `util.inspect()`.
192
193
```js
194
util.format(1, 2, 3); // '1 2 3'
195
```
196
197
If only one argument is passed to `util.format()`, it is returned as it is
198
without any formatting.
199
200
```js
201
util.format('%% %s'); // '%% %s'
202
```
203
204
## util.inherits(constructor, superConstructor)
205
<!-- YAML
206
added: v0.3.0
207
changes:
208
- version: v5.0.0
209
pr-url: https://github.com/nodejs/node/pull/3455
210
description: The `constructor` parameter can refer to an ES6 class now.
211
-->
212
213
*Note*: Usage of `util.inherits()` is discouraged. Please use the ES6 `class`
214
and `extends` keywords to get language level inheritance support. Also note
215
that the two styles are [semantically incompatible][].
216
217
* `constructor` {Function}
218
* `superConstructor` {Function}
219
220
Inherit the prototype methods from one [constructor][] into another. The
221
prototype of `constructor` will be set to a new object created from
222
`superConstructor`.
223
224
As an additional convenience, `superConstructor` will be accessible
225
through the `constructor.super_` property.
226
227
```js
228
const util = require('util');
229
const EventEmitter = require('events');
230
231
function MyStream() {
232
EventEmitter.call(this);
233
}
234
235
util.inherits(MyStream, EventEmitter);
236
237
MyStream.prototype.write = function(data) {
238
this.emit('data', data);
239
};
240
241
const stream = new MyStream();
242
243
console.log(stream instanceof EventEmitter); // true
244
console.log(MyStream.super_ === EventEmitter); // true
245
246
stream.on('data', (data) => {
247
console.log(`Received data: "${data}"`);
248
});
249
stream.write('It works!'); // Received data: "It works!"
250
```
251
252
ES6 example using `class` and `extends`
253
254
```js
255
const EventEmitter = require('events');
256
257
class MyStream extends EventEmitter {
258
write(data) {
259
this.emit('data', data);
260
}
261
}
262
263
const stream = new MyStream();
264
265
stream.on('data', (data) => {
266
console.log(`Received data: "${data}"`);
267
});
268
stream.write('With ES6');
269
270
```
271
272
## util.inspect(object[, options])
273
<!-- YAML
274
added: v0.3.0
275
changes:
276
- version: v6.6.0
277
pr-url: https://github.com/nodejs/node/pull/8174
278
description: Custom inspection functions can now return `this`.
279
- version: v6.3.0
280
pr-url: https://github.com/nodejs/node/pull/7499
281
description: The `breakLength` option is supported now.
282
- version: v6.1.0
283
pr-url: https://github.com/nodejs/node/pull/6334
284
description: The `maxArrayLength` option is supported now; in particular,
285
long arrays are truncated by default.
286
- version: v6.1.0
287
pr-url: https://github.com/nodejs/node/pull/6465
288
description: The `showProxy` option is supported now.
289
-->
290
291
* `object` {any} Any JavaScript primitive or Object.
292
* `options` {Object}
293
* `showHidden` {boolean} If `true`, the `object`'s non-enumerable symbols and
294
properties will be included in the formatted result. Defaults to `false`.
295
* `depth` {number} Specifies the number of times to recurse while formatting
296
the `object`. This is useful for inspecting large complicated objects.
297
Defaults to `2`. To make it recurse indefinitely pass `null`.
298
* `colors` {boolean} If `true`, the output will be styled with ANSI color
299
codes. Defaults to `false`. Colors are customizable, see
300
[Customizing `util.inspect` colors][].
301
* `customInspect` {boolean} If `false`, then custom `inspect(depth, opts)`
302
functions exported on the `object` being inspected will not be called.
303
Defaults to `true`.
304
* `showProxy` {boolean} If `true`, then objects and functions that are
305
`Proxy` objects will be introspected to show their `target` and `handler`
306
objects. Defaults to `false`.
307
* `maxArrayLength` {number} Specifies the maximum number of array and
308
`TypedArray` elements to include when formatting. Defaults to `100`. Set to
309
`null` to show all array elements. Set to `0` or negative to show no array
310
elements.
311
* `breakLength` {number} The length at which an object's keys are split
312
across multiple lines. Set to `Infinity` to format an object as a single
313
line. Defaults to 60 for legacy compatibility.
314
315
The `util.inspect()` method returns a string representation of `object` that is
316
primarily useful for debugging. Additional `options` may be passed that alter
317
certain aspects of the formatted string.
318
319
The following example inspects all properties of the `util` object:
320
321
```js
322
const util = require('util');
323
324
console.log(util.inspect(util, { showHidden: true, depth: null }));
325
```
326
327
Values may supply their own custom `inspect(depth, opts)` functions, when
328
called these receive the current `depth` in the recursive inspection, as well as
329
the options object passed to `util.inspect()`.
330
331
### Customizing `util.inspect` colors
332
333
<!-- type=misc -->
334
335
Color output (if enabled) of `util.inspect` is customizable globally
336
via the `util.inspect.styles` and `util.inspect.colors` properties.
337
338
`util.inspect.styles` is a map associating a style name to a color from
339
`util.inspect.colors`.
340
341
The default styles and associated colors are:
342
343
* `number` - `yellow`
344
* `boolean` - `yellow`
345
* `string` - `green`
346
* `date` - `magenta`
347
* `regexp` - `red`
348
* `null` - `bold`
349
* `undefined` - `grey`
350
* `special` - `cyan` (only applied to functions at this time)
351
* `name` - (no styling)
352
353
The predefined color codes are: `white`, `grey`, `black`, `blue`, `cyan`,
354
`green`, `magenta`, `red` and `yellow`. There are also `bold`, `italic`,
355
`underline` and `inverse` codes.
356
357
Color styling uses ANSI control codes that may not be supported on all
358
terminals.
359
360
### Custom inspection functions on Objects
361
362
<!-- type=misc -->
363
364
Objects may also define their own `[util.inspect.custom](depth, opts)`
365
(or, equivalently `inspect(depth, opts)`) function that `util.inspect()` will
366
invoke and use the result of when inspecting the object:
367
368
```js
369
const util = require('util');
370
371
class Box {
372
constructor(value) {
373
this.value = value;
374
}
375
376
inspect(depth, options) {
377
if (depth < 0) {
378
return options.stylize('[Box]', 'special');
379
}
380
381
const newOptions = Object.assign({}, options, {
382
depth: options.depth === null ? null : options.depth - 1
383
});
384
385
// Five space padding because that's the size of "Box< ".
386
const padding = ' '.repeat(5);
387
const inner = util.inspect(this.value, newOptions)
388
.replace(/\n/g, `\n${padding}`);
389
return `${options.stylize('Box', 'special')}< ${inner} >`;
390
}
391
}
392
393
const box = new Box(true);
394
395
util.inspect(box);
396
// Returns: "Box< true >"
397
```
398
399
Custom `[util.inspect.custom](depth, opts)` functions typically return a string
400
but may return a value of any type that will be formatted accordingly by
401
`util.inspect()`.
402
403
```js
404
const util = require('util');
405
406
const obj = { foo: 'this will not show up in the inspect() output' };
407
obj[util.inspect.custom] = function(depth) {
408
return { bar: 'baz' };
409
};
410
411
util.inspect(obj);
412
// Returns: "{ bar: 'baz' }"
413
```
414
415
A custom inspection method can alternatively be provided by exposing
416
an `inspect(depth, opts)` method on the object:
417
418
```js
419
const util = require('util');
420
421
const obj = { foo: 'this will not show up in the inspect() output' };
422
obj.inspect = function(depth) {
423
return { bar: 'baz' };
424
};
425
426
util.inspect(obj);
427
// Returns: "{ bar: 'baz' }"
428
```
429
430
### util.inspect.custom
431
<!-- YAML
432
added: v6.6.0
433
-->
434
435
A Symbol that can be used to declare custom inspect functions, see
436
[Custom inspection functions on Objects][].
437
438
### util.inspect.defaultOptions
439
<!-- YAML
440
added: v6.4.0
441
-->
442
443
The `defaultOptions` value allows customization of the default options used by
444
`util.inspect`. This is useful for functions like `console.log` or
445
`util.format` which implicitly call into `util.inspect`. It shall be set to an
446
object containing one or more valid [`util.inspect()`][] options. Setting
447
option properties directly is also supported.
448
449
```js
450
const util = require('util');
451
const arr = Array(101).fill(0);
452
453
console.log(arr); // logs the truncated array
454
util.inspect.defaultOptions.maxArrayLength = null;
455
console.log(arr); // logs the full array
456
```
457
458
## util.promisify(original)
459
<!-- YAML
460
added: v8.0.0
461
-->
462
463
* `original` {Function}
464
465
Takes a function following the common Node.js callback style, i.e. taking a
466
`(err, value) => ...` callback as the last argument, and returns a version
467
that returns promises.
468
469
For example:
470
471
```js
472
const util = require('util');
473
const fs = require('fs');
474
475
const stat = util.promisify(fs.stat);
476
stat('.').then((stats) => {
477
// Do something with `stats`
478
}).catch((error) => {
479
// Handle the error.
480
});
481
```
482
483
Or, equivalently using `async function`s:
484
485
```js
486
const util = require('util');
487
const fs = require('fs');
488
489
const stat = util.promisify(fs.stat);
490
491
async function callStat() {
492
const stats = await stat('.');
493
console.log(`This directory is owned by ${stats.uid}`);
494
}
495
```
496
497
If there is an `original[util.promisify.custom]` property present, `promisify`
498
will return its value, see [Custom promisified functions][].
499
500
`promisify()` assumes that `original` is a function taking a callback as its
501
final argument in all cases, and the returned function will result in undefined
502
behavior if it does not.
503
504
### Custom promisified functions
505
506
Using the `util.promisify.custom` symbol one can override the return value of
507
[`util.promisify()`][]:
508
509
```js
510
const util = require('util');
511
512
function doSomething(foo, callback) {
513
// ...
514
}
515
516
doSomething[util.promisify.custom] = function(foo) {
517
return getPromiseSomehow();
518
};
519
520
const promisified = util.promisify(doSomething);
521
console.log(promisified === doSomething[util.promisify.custom]);
522
// prints 'true'
523
```
524
525
This can be useful for cases where the original function does not follow the
526
standard format of taking an error-first callback as the last argument.
527
528
### util.promisify.custom
529
<!-- YAML
530
added: v8.0.0
531
-->
532
533
* {symbol}
534
535
A Symbol that can be used to declare custom promisified variants of functions,
536
see [Custom promisified functions][].
537
538
## Deprecated APIs
539
540
The following APIs have been deprecated and should no longer be used. Existing
541
applications and modules should be updated to find alternative approaches.
542
543
### util.\_extend(target, source)
544
<!-- YAML
545
added: v0.7.5
546
deprecated: v6.0.0
547
-->
548
549
> Stability: 0 - Deprecated: Use [`Object.assign()`] instead.
550
551
The `util._extend()` method was never intended to be used outside of internal
552
Node.js modules. The community found and used it anyway.
553
554
It is deprecated and should not be used in new code. JavaScript comes with very
555
similar built-in functionality through [`Object.assign()`].
556
557
### util.debug(string)
558
<!-- YAML
559
added: v0.3.0
560
deprecated: v0.11.3
561
-->
562
563
> Stability: 0 - Deprecated: Use [`console.error()`][] instead.
564
565
* `string` {string} The message to print to `stderr`
566
567
Deprecated predecessor of `console.error`.
568
569
### util.error([...strings])
570
<!-- YAML
571
added: v0.3.0
572
deprecated: v0.11.3
573
-->
574
575
> Stability: 0 - Deprecated: Use [`console.error()`][] instead.
576
577
* `...strings` {string} The message to print to `stderr`
578
579
Deprecated predecessor of `console.error`.
580
581
### util.isArray(object)
582
<!-- YAML
583
added: v0.6.0
584
deprecated: v4.0.0
585
-->
586
587
> Stability: 0 - Deprecated
588
589
* `object` {any}
590
591
Internal alias for [`Array.isArray`][].
592
593
Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`.
594
595
```js
596
const util = require('util');
597
598
util.isArray([]);
599
// Returns: true
600
util.isArray(new Array());
601
// Returns: true
602
util.isArray({});
603
// Returns: false
604
```
605
606
### util.isBoolean(object)
607
<!-- YAML
608
added: v0.11.5
609
deprecated: v4.0.0
610
-->
611
612
> Stability: 0 - Deprecated
613
614
* `object` {any}
615
616
Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`.
617
618
```js
619
const util = require('util');
620
621
util.isBoolean(1);
622
// Returns: false
623
util.isBoolean(0);
624
// Returns: false
625
util.isBoolean(false);
626
// Returns: true
627
```
628
629
### util.isBuffer(object)
630
<!-- YAML
631
added: v0.11.5
632
deprecated: v4.0.0
633
-->
634
635
> Stability: 0 - Deprecated: Use [`Buffer.isBuffer()`][] instead.
636
637
* `object` {any}
638
639
Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`.
640
641
```js
642
const util = require('util');
643
644
util.isBuffer({ length: 0 });
645
// Returns: false
646
util.isBuffer([]);
647
// Returns: false
648
util.isBuffer(Buffer.from('hello world'));
649
// Returns: true
650
```
651
652
### util.isDate(object)
653
<!-- YAML
654
added: v0.6.0
655
deprecated: v4.0.0
656
-->
657
658
> Stability: 0 - Deprecated
659
660
* `object` {any}
661
662
Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`.
663
664
```js
665
const util = require('util');
666
667
util.isDate(new Date());
668
// Returns: true
669
util.isDate(Date());
670
// false (without 'new' returns a String)
671
util.isDate({});
672
// Returns: false
673
```
674
675
### util.isError(object)
676
<!-- YAML
677
added: v0.6.0
678
deprecated: v4.0.0
679
-->
680
681
> Stability: 0 - Deprecated
682
683
* `object` {any}
684
685
Returns `true` if the given `object` is an [`Error`][]. Otherwise, returns
686
`false`.
687
688
```js
689
const util = require('util');
690
691
util.isError(new Error());
692
// Returns: true
693
util.isError(new TypeError());
694
// Returns: true
695
util.isError({ name: 'Error', message: 'an error occurred' });
696
// Returns: false
697
```
698
699
Note that this method relies on `Object.prototype.toString()` behavior. It is
700
possible to obtain an incorrect result when the `object` argument manipulates
701
`@@toStringTag`.
702
703
```js
704
const util = require('util');
705
const obj = { name: 'Error', message: 'an error occurred' };
706
707
util.isError(obj);
708
// Returns: false
709
obj[Symbol.toStringTag] = 'Error';
710
util.isError(obj);
711
// Returns: true
712
```
713
714
### util.isFunction(object)
715
<!-- YAML
716
added: v0.11.5
717
deprecated: v4.0.0
718
-->
719
720
> Stability: 0 - Deprecated
721
722
* `object` {any}
723
724
Returns `true` if the given `object` is a `Function`. Otherwise, returns
725
`false`.
726
727
```js
728
const util = require('util');
729
730
function Foo() {}
731
const Bar = () => {};
732
733
util.isFunction({});
734
// Returns: false
735
util.isFunction(Foo);
736
// Returns: true
737
util.isFunction(Bar);
738
// Returns: true
739
```
740
741
### util.isNull(object)
742
<!-- YAML
743
added: v0.11.5
744
deprecated: v4.0.0
745
-->
746
747
> Stability: 0 - Deprecated
748
749
* `object` {any}
750
751
Returns `true` if the given `object` is strictly `null`. Otherwise, returns
752
`false`.
753
754
```js
755
const util = require('util');
756
757
util.isNull(0);
758
// Returns: false
759
util.isNull(undefined);
760
// Returns: false
761
util.isNull(null);
762
// Returns: true
763
```
764
765
### util.isNullOrUndefined(object)
766
<!-- YAML
767
added: v0.11.5
768
deprecated: v4.0.0
769
-->
770
771
> Stability: 0 - Deprecated
772
773
* `object` {any}
774
775
Returns `true` if the given `object` is `null` or `undefined`. Otherwise,
776
returns `false`.
777
778
```js
779
const util = require('util');
780
781
util.isNullOrUndefined(0);
782
// Returns: false
783
util.isNullOrUndefined(undefined);
784
// Returns: true
785
util.isNullOrUndefined(null);
786
// Returns: true
787
```
788
789
### util.isNumber(object)
790
<!-- YAML
791
added: v0.11.5
792
deprecated: v4.0.0
793
-->
794
795
> Stability: 0 - Deprecated
796
797
* `object` {any}
798
799
Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`.
800
801
```js
802
const util = require('util');
803
804
util.isNumber(false);
805
// Returns: false
806
util.isNumber(Infinity);
807
// Returns: true
808
util.isNumber(0);
809
// Returns: true
810
util.isNumber(NaN);
811
// Returns: true
812
```
813
814
### util.isObject(object)
815
<!-- YAML
816
added: v0.11.5
817
deprecated: v4.0.0
818
-->
819
820
> Stability: 0 - Deprecated
821
822
* `object` {any}
823
824
Returns `true` if the given `object` is strictly an `Object` **and** not a
825
`Function`. Otherwise, returns `false`.
826
827
```js
828
const util = require('util');
829
830
util.isObject(5);
831
// Returns: false
832
util.isObject(null);
833
// Returns: false
834
util.isObject({});
835
// Returns: true
836
util.isObject(function() {});
837
// Returns: false
838
```
839
840
### util.isPrimitive(object)
841
<!-- YAML
842
added: v0.11.5
843
deprecated: v4.0.0
844
-->
845
846
> Stability: 0 - Deprecated
847
848
* `object` {any}
849
850
Returns `true` if the given `object` is a primitive type. Otherwise, returns
851
`false`.
852
853
```js
854
const util = require('util');
855
856
util.isPrimitive(5);
857
// Returns: true
858
util.isPrimitive('foo');
859
// Returns: true
860
util.isPrimitive(false);
861
// Returns: true
862
util.isPrimitive(null);
863
// Returns: true
864
util.isPrimitive(undefined);
865
// Returns: true
866
util.isPrimitive({});
867
// Returns: false
868
util.isPrimitive(function() {});
869
// Returns: false
870
util.isPrimitive(/^$/);
871
// Returns: false
872
util.isPrimitive(new Date());
873
// Returns: false
874
```
875
876
### util.isRegExp(object)
877
<!-- YAML
878
added: v0.6.0
879
deprecated: v4.0.0
880
-->
881
882
> Stability: 0 - Deprecated
883
884
* `object` {any}
885
886
Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`.
887
888
```js
889
const util = require('util');
890
891
util.isRegExp(/some regexp/);
892
// Returns: true
893
util.isRegExp(new RegExp('another regexp'));
894
// Returns: true
895
util.isRegExp({});
896
// Returns: false
897
```
898
899
### util.isString(object)
900
<!-- YAML
901
added: v0.11.5
902
deprecated: v4.0.0
903
-->
904
905
> Stability: 0 - Deprecated
906
907
* `object` {any}
908
909
Returns `true` if the given `object` is a `string`. Otherwise, returns `false`.
910
911
```js
912
const util = require('util');
913
914
util.isString('');
915
// Returns: true
916
util.isString('foo');
917
// Returns: true
918
util.isString(String('foo'));
919
// Returns: true
920
util.isString(5);
921
// Returns: false
922
```
923
924
### util.isSymbol(object)
925
<!-- YAML
926
added: v0.11.5
927
deprecated: v4.0.0
928
-->
929
930
> Stability: 0 - Deprecated
931
932
* `object` {any}
933
934
Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`.
935
936
```js
937
const util = require('util');
938
939
util.isSymbol(5);
940
// Returns: false
941
util.isSymbol('foo');
942
// Returns: false
943
util.isSymbol(Symbol('foo'));
944
// Returns: true
945
```
946
947
### util.isUndefined(object)
948
<!-- YAML
949
added: v0.11.5
950
deprecated: v4.0.0
951
-->
952
953
> Stability: 0 - Deprecated
954
955
* `object` {any}
956
957
Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`.
958
959
```js
960
const util = require('util');
961
962
const foo = undefined;
963
util.isUndefined(5);
964
// Returns: false
965
util.isUndefined(foo);
966
// Returns: true
967
util.isUndefined(null);
968
// Returns: false
969
```
970
971
### util.log(string)
972
<!-- YAML
973
added: v0.3.0
974
deprecated: v6.0.0
975
-->
976
977
> Stability: 0 - Deprecated: Use a third party module instead.
978
979
* `string` {string}
980
981
The `util.log()` method prints the given `string` to `stdout` with an included
982
timestamp.
983
984
```js
985
const util = require('util');
986
987
util.log('Timestamped message.');
988
```
989
990
### util.print([...strings])
991
<!-- YAML
992
added: v0.3.0
993
deprecated: v0.11.3
994
-->
995
996
> Stability: 0 - Deprecated: Use [`console.log()`][] instead.
997
998
Deprecated predecessor of `console.log`.
999
1000
### util.puts([...strings])