0
# Utilities
1
2
Core utility functions for inheritance, deprecation warnings, debugging, object extension, and timestamp logging.
3
4
## Capabilities
5
6
### Inheritance
7
8
Classical inheritance helper for constructor functions.
9
10
```javascript { .api }
11
/**
12
* Inherit prototype methods from one constructor into another
13
* @param {Function} ctor - Constructor function which needs to inherit the prototype
14
* @param {Function} superCtor - Constructor function to inherit prototype from
15
*/
16
function inherits(ctor, superCtor): void;
17
```
18
19
Sets up prototype chain so that `ctor` instances inherit from `superCtor.prototype`. This is a standalone version of the inheritance pattern, not dependent on Function.prototype.
20
21
**Usage Examples:**
22
23
```javascript
24
const util = require('util');
25
const EventEmitter = require('events');
26
27
// Define a custom class
28
function MyEmitter() {
29
EventEmitter.call(this);
30
}
31
32
// Set up inheritance
33
util.inherits(MyEmitter, EventEmitter);
34
35
// Add custom methods
36
MyEmitter.prototype.greet = function(name) {
37
this.emit('greeting', `Hello, ${name}!`);
38
};
39
40
// Usage
41
const emitter = new MyEmitter();
42
emitter.on('greeting', (message) => {
43
console.log(message);
44
});
45
emitter.greet('World'); // Emits: "Hello, World!"
46
47
// Verify inheritance
48
console.log(emitter instanceof MyEmitter); // true
49
console.log(emitter instanceof EventEmitter); // true
50
```
51
52
### Deprecation
53
54
Function wrapper that emits deprecation warnings.
55
56
```javascript { .api }
57
/**
58
* Wraps a function to emit deprecation warnings when called
59
* @param {Function} fn - Function to wrap
60
* @param {string} msg - Deprecation message
61
* @returns {Function} Wrapped function that warns on first call
62
*/
63
function deprecate(fn, msg): Function;
64
```
65
66
Behavior depends on Node.js process flags:
67
- `process.noDeprecation === true`: Returns original function without warnings
68
- `process.throwDeprecation === true`: Throws error instead of warning
69
- `process.traceDeprecation === true`: Prints stack trace with warning
70
- Default: Prints warning to stderr on first call
71
72
**Usage Examples:**
73
74
```javascript
75
const util = require('util');
76
77
// Deprecate a function
78
function oldFunction() {
79
return 'This is deprecated';
80
}
81
82
const deprecatedFunction = util.deprecate(
83
oldFunction,
84
'oldFunction is deprecated. Use newFunction instead.'
85
);
86
87
// First call shows warning, subsequent calls are silent
88
deprecatedFunction(); // Shows warning + returns result
89
deprecatedFunction(); // Only returns result
90
91
// Example with replacement suggestion
92
const oldAPI = util.deprecate(
93
function(data) {
94
return processLegacyData(data);
95
},
96
'oldAPI is deprecated. Use newAPI with updated parameters.'
97
);
98
```
99
100
### Debug Logging
101
102
Conditional debug logging based on NODE_DEBUG environment variable.
103
104
```javascript { .api }
105
/**
106
* Creates a debug logging function for the specified module
107
* @param {string} set - Debug namespace/module name
108
* @returns {Function} Debug logging function (noop if not enabled)
109
*/
110
function debuglog(set): Function;
111
```
112
113
Returns a logging function that only outputs when `NODE_DEBUG` environment variable includes the specified set name. Supports wildcards and comma-separated lists.
114
115
**Usage Examples:**
116
117
```javascript
118
const util = require('util');
119
120
// Create debug logger
121
const debug = util.debuglog('mymodule');
122
123
// Use debug logger (only outputs if NODE_DEBUG includes 'mymodule')
124
debug('Starting initialization');
125
debug('Processing item %s', itemName);
126
127
// Environment variable examples:
128
// NODE_DEBUG=mymodule node app.js // Shows mymodule logs
129
// NODE_DEBUG=mymodule,http node app.js // Shows mymodule and http logs
130
// NODE_DEBUG=* node app.js // Shows all debug logs
131
// NODE_DEBUG=my* node app.js // Shows logs matching my*
132
133
// Multiple debug loggers
134
const httpDebug = util.debuglog('http');
135
const dbDebug = util.debuglog('database');
136
137
httpDebug('HTTP request received');
138
dbDebug('Database query executed');
139
```
140
141
### Object Extension
142
143
Extends an object with properties from another object.
144
145
```javascript { .api }
146
/**
147
* Extends an object with properties from another object
148
* @param {Object} origin - Target object to extend
149
* @param {Object} add - Source object to copy properties from
150
* @returns {Object} The extended origin object
151
*/
152
function _extend(origin, add): Object;
153
```
154
155
Copies enumerable own properties from `add` to `origin`. Returns the `origin` object. If `add` is not an object, returns `origin` unchanged.
156
157
**Usage Examples:**
158
159
```javascript
160
const util = require('util');
161
162
// Basic extension
163
const defaults = { timeout: 5000, retries: 3 };
164
const options = { timeout: 10000 };
165
166
const config = util._extend(defaults, options);
167
console.log(config); // { timeout: 10000, retries: 3 }
168
169
// Extension with null/undefined (returns origin unchanged)
170
const base = { a: 1 };
171
util._extend(base, null); // { a: 1 }
172
util._extend(base, undefined); // { a: 1 }
173
174
// Modifies original object
175
const original = { x: 1 };
176
const result = util._extend(original, { y: 2 });
177
console.log(original === result); // true
178
console.log(original); // { x: 1, y: 2 }
179
```
180
181
### Timestamp Logging
182
183
Console logging with timestamp prefix.
184
185
```javascript { .api }
186
/**
187
* Logs to console with timestamp prefix
188
* @param {...any} args - Arguments to log (same as console.log)
189
*/
190
function log(...args): void;
191
```
192
193
Outputs to console.log with a timestamp in "DD MMM HH:MM:SS" format. Arguments are formatted using the `format` function.
194
195
**Usage Examples:**
196
197
```javascript
198
const util = require('util');
199
200
// Basic logging with timestamp
201
util.log('Server started');
202
// Output: "5 Dec 14:30:15 - Server started"
203
204
// Multiple arguments
205
util.log('User %s logged in from %s', 'alice', '192.168.1.1');
206
// Output: "5 Dec 14:30:16 - User alice logged in from 192.168.1.1"
207
208
// Objects are inspected
209
util.log('Config loaded:', { port: 3000, env: 'production' });
210
// Output: "5 Dec 14:30:17 - Config loaded: { port: 3000, env: 'production' }"
211
```