Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 288 lines (187 sloc) 8.232 kB
b431012 @tj Added node.util.md
authored
1 # util
2
328f9ce @tj update node
authored
3 Stability: 4 - API Frozen
b431012 @tj Added node.util.md
authored
4
328f9ce @tj update node
authored
5 These functions are in the module `'util'`. Use `require('util')` to
6 access them.
b431012 @tj Added node.util.md
authored
7
328f9ce @tj update node
authored
8 The `util` module is primarily designed to support the needs of Node's
9 internal APIs. Many of these utilities are useful for your own
10 programs. If you find that these functions are lacking for your
11 purposes, however, you are encouraged to write your own utilities. We
12 are not interested in any future additions to the `util` module that
13 are unnecessary for Node's internal functionality.
14
15 ## util.debuglog(section)
16
17 * `section` {String} The section of the program to be debugged
18 * Returns: {Function} The logging function
19
20 This is used to create a function which conditionally writes to stderr
21 based on the existence of a `NODE_DEBUG` environment variable. If the
22 `section` name appears in that environment variable, then the returned
23 function will be similar to `console.error()`. If not, then the
24 returned function is a no-op.
25
26 For example:
27
28 ```javascript
29 var debuglog = util.debuglog('foo');
30
31 var bar = 123;
32 debuglog('hello from foo [%d]', bar);
33 ```
34
35 If this program is run with `NODE_DEBUG=foo` in the environment, then
36 it will output something like:
37
38 FOO 3245: hello from foo [123]
39
40 where `3245` is the process id. If it is not run with that
41 environment variable set, then it will not print anything.
42
43 You may separate multiple `NODE_DEBUG` environment variables with a
44 comma. For example, `NODE_DEBUG=fs,net,tls`.
b431012 @tj Added node.util.md
authored
45
46 ## util.format(format, [...])
47
48 Returns a formatted string using the first argument as a `printf`-like format.
49
50 The first argument is a string that contains zero or more *placeholders*.
51 Each placeholder is replaced with the converted value from its corresponding
52 argument. Supported placeholders are:
53
54 * `%s` - String.
55 * `%d` - Number (both integer and float).
328f9ce @tj update node
authored
56 * `%j` - JSON. Replaced with the string `'[Circular]'` if the argument
57 contains circular references.
b431012 @tj Added node.util.md
authored
58 * `%%` - single percent sign (`'%'`). This does not consume an argument.
59
60 If the placeholder does not have a corresponding argument, the placeholder is
61 not replaced.
62
63 util.format('%s:%s', 'foo'); // 'foo:%s'
64
65 If there are more arguments than placeholders, the extra arguments are
66 converted to strings with `util.inspect()` and these strings are concatenated,
67 delimited by a space.
68
69 util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'
70
71 If the first argument is not a format string then `util.format()` returns
72 a string that is the concatenation of all its arguments separated by spaces.
73 Each argument is converted to a string with `util.inspect()`.
74
75 util.format(1, 2, 3); // '1 2 3'
76
77
328f9ce @tj update node
authored
78 ## util.log(string)
b431012 @tj Added node.util.md
authored
79
328f9ce @tj update node
authored
80 Output with timestamp on `stdout`.
b431012 @tj Added node.util.md
authored
81
328f9ce @tj update node
authored
82 require('util').log('Timestamped message.');
b431012 @tj Added node.util.md
authored
83
328f9ce @tj update node
authored
84 ## util.inspect(object, [options])
b431012 @tj Added node.util.md
authored
85
328f9ce @tj update node
authored
86 Return a string representation of `object`, which is useful for debugging.
b431012 @tj Added node.util.md
authored
87
328f9ce @tj update node
authored
88 An optional *options* object may be passed that alters certain aspects of the
89 formatted string:
b431012 @tj Added node.util.md
authored
90
328f9ce @tj update node
authored
91 - `showHidden` - if `true` then the object's non-enumerable properties will be
92 shown too. Defaults to `false`.
b431012 @tj Added node.util.md
authored
93
328f9ce @tj update node
authored
94 - `depth` - tells `inspect` how many times to recurse while formatting the
95 object. This is useful for inspecting large complicated objects. Defaults to
96 `2`. To make it recurse indefinitely pass `null`.
b431012 @tj Added node.util.md
authored
97
328f9ce @tj update node
authored
98 - `colors` - if `true`, then the output will be styled with ANSI color codes.
99 Defaults to `false`. Colors are customizable, see below.
b431012 @tj Added node.util.md
authored
100
328f9ce @tj update node
authored
101 - `customInspect` - if `false`, then custom `inspect(depth, opts)` functions
102 defined on the objects being inspected won't be called. Defaults to `true`.
b431012 @tj Added node.util.md
authored
103
328f9ce @tj update node
authored
104 Example of inspecting all properties of the `util` object:
b431012 @tj Added node.util.md
authored
105
328f9ce @tj update node
authored
106 var util = require('util');
b431012 @tj Added node.util.md
authored
107
328f9ce @tj update node
authored
108 console.log(util.inspect(util, { showHidden: true, depth: null }));
b431012 @tj Added node.util.md
authored
109
328f9ce @tj update node
authored
110 Values may supply their own custom `inspect(depth, opts)` functions, when
111 called they receive the current depth in the recursive inspection, as well as
112 the options object passed to `util.inspect()`.
b431012 @tj Added node.util.md
authored
113
328f9ce @tj update node
authored
114 ### Customizing `util.inspect` colors
b431012 @tj Added node.util.md
authored
115
328f9ce @tj update node
authored
116 <!-- type=misc -->
b431012 @tj Added node.util.md
authored
117
328f9ce @tj update node
authored
118 Color output (if enabled) of `util.inspect` is customizable globally
119 via `util.inspect.styles` and `util.inspect.colors` objects.
b431012 @tj Added node.util.md
authored
120
328f9ce @tj update node
authored
121 `util.inspect.styles` is a map assigning each style a color
122 from `util.inspect.colors`.
123 Highlighted styles and their default values are:
124 * `number` (yellow)
125 * `boolean` (yellow)
126 * `string` (green)
127 * `date` (magenta)
128 * `regexp` (red)
129 * `null` (bold)
130 * `undefined` (grey)
131 * `special` - only function at this time (cyan)
132 * `name` (intentionally no styling)
b431012 @tj Added node.util.md
authored
133
328f9ce @tj update node
authored
134 Predefined color codes are: `white`, `grey`, `black`, `blue`, `cyan`,
135 `green`, `magenta`, `red` and `yellow`.
136 There are also `bold`, `italic`, `underline` and `inverse` codes.
b431012 @tj Added node.util.md
authored
137
328f9ce @tj update node
authored
138 ### Custom `inspect()` function on Objects
139
140 <!-- type=misc -->
141
142 Objects also may define their own `inspect(depth)` function which `util.inspect()`
143 will invoke and use the result of when inspecting the object:
b431012 @tj Added node.util.md
authored
144
145 var util = require('util');
146
328f9ce @tj update node
authored
147 var obj = { name: 'nate' };
148 obj.inspect = function(depth) {
149 return '{' + this.name + '}';
150 };
151
152 util.inspect(obj);
153 // "{nate}"
154
155 You may also return another Object entirely, and the returned String will be
156 formatted according to the returned Object. This is similar to how
157 `JSON.stringify()` works:
158
159 var obj = { foo: 'this will not show up in the inspect() output' };
160 obj.inspect = function(depth) {
161 return { bar: 'baz' };
162 };
163
164 util.inspect(obj);
165 // "{ bar: 'baz' }"
b431012 @tj Added node.util.md
authored
166
167
168 ## util.isArray(object)
169
170 Returns `true` if the given "object" is an `Array`. `false` otherwise.
171
172 var util = require('util');
173
174 util.isArray([])
175 // true
176 util.isArray(new Array)
177 // true
178 util.isArray({})
179 // false
180
181
182 ## util.isRegExp(object)
183
184 Returns `true` if the given "object" is a `RegExp`. `false` otherwise.
185
186 var util = require('util');
187
188 util.isRegExp(/some regexp/)
189 // true
190 util.isRegExp(new RegExp('another regexp'))
191 // true
192 util.isRegExp({})
193 // false
194
195
196 ## util.isDate(object)
197
198 Returns `true` if the given "object" is a `Date`. `false` otherwise.
199
200 var util = require('util');
201
202 util.isDate(new Date())
203 // true
204 util.isDate(Date())
205 // false (without 'new' returns a String)
206 util.isDate({})
207 // false
208
209
210 ## util.isError(object)
211
212 Returns `true` if the given "object" is an `Error`. `false` otherwise.
213
214 var util = require('util');
215
216 util.isError(new Error())
217 // true
218 util.isError(new TypeError())
219 // true
220 util.isError({ name: 'Error', message: 'an error occurred' })
221 // false
222
223
224 ## util.inherits(constructor, superConstructor)
225
226 Inherit the prototype methods from one
227 [constructor](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor)
228 into another. The prototype of `constructor` will be set to a new
229 object created from `superConstructor`.
230
231 As an additional convenience, `superConstructor` will be accessible
232 through the `constructor.super_` property.
233
234 var util = require("util");
235 var events = require("events");
236
237 function MyStream() {
238 events.EventEmitter.call(this);
239 }
240
241 util.inherits(MyStream, events.EventEmitter);
242
243 MyStream.prototype.write = function(data) {
244 this.emit("data", data);
245 }
246
247 var stream = new MyStream();
248
249 console.log(stream instanceof events.EventEmitter); // true
250 console.log(MyStream.super_ === events.EventEmitter); // true
251
252 stream.on("data", function(data) {
253 console.log('Received data: "' + data + '"');
254 })
255 stream.write("It works!"); // Received data: "It works!"
328f9ce @tj update node
authored
256
257
258 ## util.debug(string)
259
260 Stability: 0 - Deprecated: use console.error() instead.
261
262 Deprecated predecessor of `console.error`.
263
264 ## util.error([...])
265
266 Stability: 0 - Deprecated: Use console.error() instead.
267
268 Deprecated predecessor of `console.error`.
269
270 ## util.puts([...])
271
272 Stability: 0 - Deprecated: Use console.log() instead.
273
274 Deprecated predecessor of `console.log`.
275
276 ## util.print([...])
277
278 Stability: 0 - Deprecated: Use `console.log` instead.
279
280 Deprecated predecessor of `console.log`.
281
282
283 ## util.pump(readableStream, writableStream, [callback])
284
285 Stability: 0 - Deprecated: Use readableStream.pipe(writableStream)
286
287 Deprecated predecessor of `stream.pipe()`.
Something went wrong with that request. Please try again.