Skip to content

Commit e4c835e

Browse files
committed
doc: improvements to console.markdown copy
Several improvements including a few new examples PR-URL: #4428 Reviewed-By: Stephen Belanger <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Evan Lucas <[email protected]>
1 parent 7d5c1b5 commit e4c835e

File tree

1 file changed

+117
-53
lines changed

1 file changed

+117
-53
lines changed

doc/api/console.markdown

+117-53
Original file line numberDiff line numberDiff line change
@@ -2,29 +2,79 @@
22

33
Stability: 2 - Stable
44

5-
The module defines a `Console` class and exports a `console` object.
5+
The `console` module provides a simple debugging console that is similar to the
6+
JavaScript console mechanism provided by web browsers.
67

7-
The `console` object is a special instance of `Console` whose output is
8-
sent to stdout or stderr.
8+
The module exports two specific components:
99

10-
For ease of use, `console` is defined as a global object and can be used
11-
directly without `require`.
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 `stdout` and `stderr`.
13+
Because this object is global, it can be used without calling
14+
`require('console')`.
15+
16+
Example using the global `console`:
17+
18+
console.log('hello world');
19+
// Prints: hello world, to stdout
20+
console.log('hello %s', 'world');
21+
// Prints: hello world, to stdout
22+
console.error(new Error('Whoops, something bad happened'));
23+
// Prints: [Error: Whoops, something bad happened], to stderr
24+
25+
const name = 'Will Robinson';
26+
console.warn(`Danger ${name}! Danger!`);
27+
// Prints: Danger Will Robinson! Danger!, to stderr
28+
29+
Example using the `Console` class:
30+
31+
const out = getStreamSomehow();
32+
const err = getStreamSomehow();
33+
const myConsole = new console.Console(out, err);
34+
35+
myConsole.log('hello world');
36+
// Prints: hello world, to out
37+
myConsole.log('hello %s', 'world');
38+
// Prints: hello world, to out
39+
myConsole.error(new Error('Whoops, something bad happened'));
40+
// Prints: [Error: Whoops, something bad happened], to err
41+
42+
const name = 'Will Robinson';
43+
myConsole.warn(`Danger ${name}! Danger!`);
44+
// Prints: Danger Will Robinson! Danger!, to err
45+
46+
While the API for the `Console` class is designed fundamentally around the
47+
Web browser `console` object, the `Console` is Node.js is *not* intended to
48+
duplicate the browsers functionality exactly.
49+
50+
## Asynchronous vs Synchronous Consoles
51+
52+
The console functions are synchronous when the destination is a terminal or
53+
a file (to avoid lost messages in case of premature exit) and asynchronous
54+
when the destination is a pipe (to avoid blocking for long periods of time).
55+
56+
In the following example, stdout is non-blocking while stderr is blocking:
57+
58+
$ node script.js 2> error.log | tee info.log
59+
60+
Typically, the distinction between blocking/non-blocking is not important
61+
unless an application is logging significant amounts of data. High volume
62+
logging *should* use a `Console` instance that writes to a pipe.
1263

1364
## Class: Console
1465

1566
<!--type=class-->
1667

17-
Use `require('console').Console` or `console.Console` to access this class.
68+
The `Console` class can be used to create a simple logger with configurable
69+
output streams and can be accessed using either `require('console').Console`
70+
or `console.Console`:
1871

1972
const Console = require('console').Console;
2073
const Console = console.Console;
2174

22-
You can use the `Console` class to create a simple logger like `console` but
23-
with different output streams.
24-
2575
### new Console(stdout[, stderr])
2676

27-
Create a new `Console` by passing one or two writable stream instances.
77+
Creates a new `Console` by passing one or two writable stream instances.
2878
`stdout` is a writable stream to print log or info output. `stderr`
2979
is used for warning or error output. If `stderr` isn't passed, the warning
3080
and error output will be sent to the `stdout`.
@@ -39,42 +89,27 @@ and error output will be sent to the `stdout`.
3989
// in stdout.log: count 5
4090

4191
The global `console` is a special `Console` whose output is sent to
42-
`process.stdout` and `process.stderr`:
92+
`process.stdout` and `process.stderr`. It is equivalent to calling:
4393

4494
new Console(process.stdout, process.stderr);
4595

46-
## console
47-
48-
* {Object}
49-
50-
<!--type=global-->
51-
52-
For printing to stdout and stderr. Similar to the console object functions
53-
provided by most web browsers, here the output is sent to stdout or stderr.
54-
55-
The console functions are synchronous when the destination is a terminal or
56-
a file (to avoid lost messages in case of premature exit) and asynchronous
57-
when it's a pipe (to avoid blocking for long periods of time).
58-
59-
That is, in the following example, stdout is non-blocking while stderr
60-
is blocking:
61-
62-
$ node script.js 2> error.log | tee info.log
63-
64-
Typically, the blocking/non-blocking dichotomy is not something you should
65-
worry about unless you log huge amounts of data.
66-
6796
### console.assert(value[, message][, ...])
6897

69-
Similar to [`assert.ok()`][], but the error message is formatted as
70-
`util.format(message...)`.
98+
A simple assertion test that verifies whether `value` is truthy. If it is not,
99+
an `AssertionError` is throw. If provided, the error `message` is formatted
100+
using [`util.format()`][] and used as the error message.
101+
102+
console.assert(true, 'does nothing');
103+
// OK
104+
console.assert(false, 'Whoops %s', 'didn\'t work');
105+
// AssertionError: Whoops didn't work
71106

72107
### console.dir(obj[, options])
73108

74109
Uses [`util.inspect()`][] on `obj` and prints the resulting string to stdout.
75-
This function bypasses any custom `inspect()` function on `obj`. An optional
76-
`options` object may be passed that alters certain aspects of the formatted
77-
string:
110+
This function bypasses any custom `inspect()` function defined on `obj`. An
111+
optional `options` object may be passed that alters certain aspects of the
112+
formatted string:
78113

79114
- `showHidden` - if `true` then the object's non-enumerable and symbol
80115
properties will be shown too. Defaults to `false`.
@@ -89,36 +124,53 @@ Defaults to `false`. Colors are customizable; see
89124

90125
### console.error([data][, ...])
91126

92-
Same as [`console.log()`][] but prints to stderr.
127+
Prints to stderr with newline. Multiple arguments can be passed, with the first
128+
used as the primary message and all additional used as substitution
129+
values similar to `printf()` (the arguments are all passed to
130+
[`util.format()`][]).
131+
132+
const code = 5;
133+
console.error('error #%d', code);
134+
// Prints: error #5, to stderr
135+
console.error('error', code);
136+
// Prints: error 5, to stderr
137+
138+
If formatting elements (e.g. `%d`) are not found in the first string then
139+
[`util.inspect()`][] is called on each argument and the resulting string
140+
values are concatenated. See [`util.format()`][] for more information.
93141

94142
### console.info([data][, ...])
95143

96-
Same as [`console.log()`][].
144+
The `console.info()` function is an alias for [`console.log()`][].
97145

98146
### console.log([data][, ...])
99147

100-
Prints to stdout with newline. This function can take multiple arguments in a
101-
`printf()`-like way:
148+
Prints to stdout with newline. Multiple arguments can be passed, with the first
149+
used as the primary message and all additional used as substitution
150+
values similar to `printf()` (the arguments are all passed to
151+
[`util.format()`][]).
102152

103153
var count = 5;
104154
console.log('count: %d', count);
105-
// prints 'count: 5'
155+
// Prints: count: 5, to stdout
156+
console.log('count: ', count);
157+
// Prints: count: 5, to stdout
106158

107-
If formatting elements are not found in the first string then
108-
[`util.inspect()`][] is used on each argument. See [`util.format()`][] for more
109-
information.
159+
If formatting elements (e.g. `%d`) are not found in the first string then
160+
[`util.inspect()`][] is called on each argument and the resulting string
161+
values are concatenated. See [`util.format()`][] for more information.
110162

111163
### console.time(label)
112164

113165
Starts a timer that can be used to compute the duration of an operation. Timers
114-
are identified by a unique name. Use the same name when you call
166+
are identified by a unique `label`. Use the same `label` when you call
115167
[`console.timeEnd()`][] to stop the timer and output the elapsed time in
116-
milliseconds. Timer durations are accurate to the sub-millisecond.
168+
milliseconds to stdout. Timer durations are accurate to the sub-millisecond.
117169

118170
### console.timeEnd(label)
119171

120172
Stops a timer that was previously started by calling [`console.time()`][] and
121-
prints the result to the console:
173+
prints the result to stdout:
122174

123175
console.time('100-elements');
124176
for (var i = 0; i < 100; i++) {
@@ -129,18 +181,30 @@ prints the result to the console:
129181

130182
### console.trace(message[, ...])
131183

132-
Print to stderr `'Trace :'`, followed by the formatted message and stack trace
133-
to the current position.
184+
Prints to stderr the string `'Trace :'`, followed by the [`util.format()`][]
185+
formatted message and stack trace to the current position in the code.
186+
187+
console.trace('Show me');
188+
// Prints: (stack trace will vary based on where trace is called)
189+
// Trace: Show me
190+
// at repl:2:9
191+
// at REPLServer.defaultEval (repl.js:248:27)
192+
// at bound (domain.js:287:14)
193+
// at REPLServer.runBound [as eval] (domain.js:300:12)
194+
// at REPLServer.<anonymous> (repl.js:412:12)
195+
// at emitOne (events.js:82:20)
196+
// at REPLServer.emit (events.js:169:7)
197+
// at REPLServer.Interface._onLine (readline.js:210:10)
198+
// at REPLServer.Interface._line (readline.js:549:8)
199+
// at REPLServer.Interface._ttyWrite (readline.js:826:14)
134200

135201
### console.warn([data][, ...])
136202

137-
Same as [`console.error()`][].
203+
The `console.warn()` function is an alias for [`console.error()`][].
138204

139-
[`assert.ok()`]: assert.html#assert_assert_value_message_assert_ok_value_message
140205
[`console.error()`]: #console_console_error_data
141206
[`console.log()`]: #console_console_log_data
142207
[`console.time()`]: #console_console_time_label
143208
[`console.timeEnd()`]: #console_console_timeend_label
144209
[`util.format()`]: util.html#util_util_format_format
145210
[`util.inspect()`]: util.html#util_util_inspect_object_options
146-
[customizing `util.inspect()` colors]: util.html#util_customizing_util_inspect_colors

0 commit comments

Comments
 (0)