-
-
Notifications
You must be signed in to change notification settings - Fork 35.5k
Expand file tree
/
Copy pathconsole.md
More file actions
335 lines (274 loc) Β· 10.2 KB
/
console.md
File metadata and controls
335 lines (274 loc) Β· 10.2 KB
Edit and raw actions
OlderNewer
Β
1
# Console
2
3
> Stability: 2 - Stable
4
5
The `console` module provides a simple debugging console that is similar to the
6
JavaScript console mechanism provided by web browsers.
7
8
The module exports two specific components:
9
10
* A `Console` class with methods such as `console.log()`, `console.error()` and
11
`console.warn()` that can be used to write to any Node.js stream.
12
* A global `console` instance configured to write to [`process.stdout`][] and
13
[`process.stderr`][]. The global `console` can be used without calling
14
`require('console')`.
15
16
***Warning***: The global console object's methods are neither consistently
17
synchronous like the browser APIs they resemble, nor are they consistently
18
asynchronous like all other Node.js streams. See the [note on process I/O][] for
19
more information.
20
21
Example using the global `console`:
22
23
```js
24
console.log('hello world');
25
// Prints: hello world, to stdout
26
console.log('hello %s', 'world');
27
// Prints: hello world, to stdout
28
console.error(new Error('Whoops, something bad happened'));
29
// Prints: [Error: Whoops, something bad happened], to stderr
30
31
const name = 'Will Robinson';
32
console.warn(`Danger ${name}! Danger!`);
33
// Prints: Danger Will Robinson! Danger!, to stderr
34
```
35
36
Example using the `Console` class:
37
38
```js
39
const out = getStreamSomehow();
40
const err = getStreamSomehow();
41
const myConsole = new console.Console(out, err);
42
43
myConsole.log('hello world');
44
// Prints: hello world, to out
45
myConsole.log('hello %s', 'world');
46
// Prints: hello world, to out
47
myConsole.error(new Error('Whoops, something bad happened'));
48
// Prints: [Error: Whoops, something bad happened], to err
49
50
const name = 'Will Robinson';
51
myConsole.warn(`Danger ${name}! Danger!`);
52
// Prints: Danger Will Robinson! Danger!, to err
53
```
54
55
## Class: Console
56
<!-- YAML
57
changes:
58
- version: v8.0.0
59
pr-url: https://github.com/nodejs/node/pull/9744
60
description: Errors that occur while writing to the underlying streams
61
will now be ignored.
62
-->
63
64
<!--type=class-->
65
66
The `Console` class can be used to create a simple logger with configurable
67
output streams and can be accessed using either `require('console').Console`
68
or `console.Console` (or their destructured counterparts):
69
70
```js
71
const { Console } = require('console');
72
```
73
74
```js
75
const { Console } = console;
76
```
77
78
### new Console(stdout[, stderr])
79
* `stdout` {Writable}
80
* `stderr` {Writable}
81
82
Creates a new `Console` by passing one or two writable stream instances.
83
`stdout` is a writable stream to print log or info output. `stderr`
84
is used for warning or error output. If `stderr` is not passed, warning and error
85
output will be sent to `stdout`.
86
87
```js
88
const output = fs.createWriteStream('./stdout.log');
89
const errorOutput = fs.createWriteStream('./stderr.log');
90
// custom simple logger
91
const logger = new Console(output, errorOutput);
92
// use it like console
93
const count = 5;
94
logger.log('count: %d', count);
95
// in stdout.log: count 5
96
```
97
98
The global `console` is a special `Console` whose output is sent to
99
[`process.stdout`][] and [`process.stderr`][]. It is equivalent to calling:
100
101
```js
102
new Console(process.stdout, process.stderr);
103
```
104
105
### console.assert(value[, message][, ...args])
106
<!-- YAML
107
added: v0.1.101
108
-->
109
* `value` {any}
110
* `message` {any}
111
* `...args` {any}
112
113
A simple assertion test that verifies whether `value` is truthy. If it is not,
114
an `AssertionError` is thrown. If provided, the error `message` is formatted
115
using [`util.format()`][] and used as the error message.
116
117
```js
118
console.assert(true, 'does nothing');
119
// OK
120
console.assert(false, 'Whoops %s', 'didn\'t work');
121
// AssertionError: Whoops didn't work
122
```
123
124
*Note*: The `console.assert()` method is implemented differently in Node.js
125
than the `console.assert()` method [available in browsers][web-api-assert].
126
127
Specifically, in browsers, calling `console.assert()` with a falsy
128
assertion will cause the `message` to be printed to the console without
129
interrupting execution of subsequent code. In Node.js, however, a falsy
130
assertion will cause an `AssertionError` to be thrown.
131
132
Functionality approximating that implemented by browsers can be implemented
133
by extending Node.js' `console` and overriding the `console.assert()` method.
134
135
In the following example, a simple module is created that extends and overrides
136
the default behavior of `console` in Node.js.
137
138
<!-- eslint-disable func-name-matching -->
139
```js
140
'use strict';
141
142
// Creates a simple extension of console with a
143
// new impl for assert without monkey-patching.
144
const myConsole = Object.create(console, {
145
assert: {
146
value: function assert(assertion, message, ...args) {
147
try {
148
console.assert(assertion, message, ...args);
149
} catch (err) {
150
console.error(err.stack);
151
}
152
},
153
configurable: true,
154
enumerable: true,
155
writable: true,
156
},
157
});
158
159
module.exports = myConsole;
160
```
161
162
This can then be used as a direct replacement for the built in console:
163
164
```js
165
const console = require('./myConsole');
166
console.assert(false, 'this message will print, but no error thrown');
167
console.log('this will also print');
168
```
169
170
### console.dir(obj[, options])
171
<!-- YAML
172
added: v0.1.101
173
-->
174
* `obj` {any}
175
* `options` {Object}
176
* `showHidden` {boolean}
177
* `depth` {number}
178
* `colors` {boolean}
179
180
Uses [`util.inspect()`][] on `obj` and prints the resulting string to `stdout`.
181
This function bypasses any custom `inspect()` function defined on `obj`. An
182
optional `options` object may be passed to alter certain aspects of the
183
formatted string:
184
185
- `showHidden` - if `true` then the object's non-enumerable and symbol
186
properties will be shown too. Defaults to `false`.
187
188
- `depth` - tells [`util.inspect()`][] how many times to recurse while
189
formatting the object. This is useful for inspecting large complicated objects.
190
Defaults to `2`. To make it recurse indefinitely, pass `null`.
191
192
- `colors` - if `true`, then the output will be styled with ANSI color codes.
193
Defaults to `false`. Colors are customizable; see
194
[customizing `util.inspect()` colors][].
195
196
### console.error([data][, ...args])
197
<!-- YAML
198
added: v0.1.100
199
-->
200
* `data` {any}
201
* `...args` {any}
202
203
Prints to `stderr` with newline. Multiple arguments can be passed, with the
204
first used as the primary message and all additional used as substitution
205
values similar to printf(3) (the arguments are all passed to
206
[`util.format()`][]).
207
208
```js
209
const code = 5;
210
console.error('error #%d', code);
211
// Prints: error #5, to stderr
212
console.error('error', code);
213
// Prints: error 5, to stderr
214
```
215
216
If formatting elements (e.g. `%d`) are not found in the first string then
217
[`util.inspect()`][] is called on each argument and the resulting string
218
values are concatenated. See [`util.format()`][] for more information.
219
220
### console.info([data][, ...args])
221
<!-- YAML
222
added: v0.1.100
223
-->
224
* `data` {any}
225
* `...args` {any}
226
227
The `console.info()` function is an alias for [`console.log()`][].
228
229
### console.log([data][, ...args])
230
<!-- YAML
231
added: v0.1.100
232
-->
233
* `data` {any}
234
* `...args` {any}
235
236
Prints to `stdout` with newline. Multiple arguments can be passed, with the
237
first used as the primary message and all additional used as substitution
238
values similar to printf(3) (the arguments are all passed to
239
[`util.format()`][]).
240
241
```js
242
const count = 5;
243
console.log('count: %d', count);
244
// Prints: count: 5, to stdout
245
console.log('count:', count);
246
// Prints: count: 5, to stdout
247
```
248
249
If formatting elements (e.g. `%d`) are not found in the first string then
250
[`util.inspect()`][] is called on each argument and the resulting string
251
values are concatenated. See [`util.format()`][] for more information.
252
253
### console.time(label)
254
<!-- YAML
255
added: v0.1.104
256
-->
257
* `label` {string}
258
259
Starts a timer that can be used to compute the duration of an operation. Timers
260
are identified by a unique `label`. Use the same `label` when calling
261
[`console.timeEnd()`][] to stop the timer and output the elapsed time in
262
milliseconds to `stdout`. Timer durations are accurate to the sub-millisecond.
263
264
### console.timeEnd(label)
265
<!-- YAML
266
added: v0.1.104
267
changes:
268
- version: v6.0.0
269
pr-url: https://github.com/nodejs/node/pull/5901
270
description: This method no longer supports multiple calls that donβt map
271
to individual `console.time()` calls; see below for details.
272
-->
273
* `label` {string}
274
275
Stops a timer that was previously started by calling [`console.time()`][] and
276
prints the result to `stdout`:
277
278
```js
279
console.time('100-elements');
280
for (let i = 0; i < 100; i++) {}
281
console.timeEnd('100-elements');
282
// prints 100-elements: 225.438ms
283
```
284
285
*Note*: As of Node.js v6.0.0, `console.timeEnd()` deletes the timer to avoid
286
leaking it. On older versions, the timer persisted. This allowed
287
`console.timeEnd()` to be called multiple times for the same label. This
288
functionality was unintended and is no longer supported.
289
290
### console.trace([message][, ...args])
291
<!-- YAML
292
added: v0.1.104
293
-->
294
* `message` {any}
295
* `...args` {any}
296
297
Prints to `stderr` the string `'Trace :'`, followed by the [`util.format()`][]
298
formatted message and stack trace to the current position in the code.
299
300
```js
301
console.trace('Show me');
302
// Prints: (stack trace will vary based on where trace is called)
303
// Trace: Show me
304
// at repl:2:9
305
// at REPLServer.defaultEval (repl.js:248:27)
306
// at bound (domain.js:287:14)
307
// at REPLServer.runBound [as eval] (domain.js:300:12)
308
// at REPLServer.<anonymous> (repl.js:412:12)
309
// at emitOne (events.js:82:20)
310
// at REPLServer.emit (events.js:169:7)
311
// at REPLServer.Interface._onLine (readline.js:210:10)
312
// at REPLServer.Interface._line (readline.js:549:8)
313
// at REPLServer.Interface._ttyWrite (readline.js:826:14)
314
```
315
316
### console.warn([data][, ...args])
317
<!-- YAML
318
added: v0.1.100
319
-->
320
* `data` {any}
321
* `...args` {any}
322
323
The `console.warn()` function is an alias for [`console.error()`][].
324
325
[`console.error()`]: #console_console_error_data_args
326
[`console.log()`]: #console_console_log_data_args
327
[`console.time()`]: #console_console_time_label
328
[`console.timeEnd()`]: #console_console_timeend_label
329
[`process.stderr`]: process.html#process_process_stderr
330
[`process.stdout`]: process.html#process_process_stdout
331
[`util.format()`]: util.html#util_util_format_format_args
332
[`util.inspect()`]: util.html#util_util_inspect_object_options
333
[customizing `util.inspect()` colors]: util.html#util_customizing_util_inspect_colors
334
[note on process I/O]: process.html#process_a_note_on_process_i_o
335
[web-api-assert]: https://developer.mozilla.org/en-US/docs/Web/API/console/assert