Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit df7e128

Browse filesBrowse files
jasnellMyles Borins
authored andcommitted
doc: improvements to console.markdown copy
Several improvements including a few new examples PR-URL: #4428 Reviewed-By: Stephen Belanger <admin@stephenbelanger.com> Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: Evan Lucas <evanlucas@me.com>
1 parent abb17cc commit df7e128
Copy full SHA for df7e128

File tree

Expand file treeCollapse file tree

1 file changed

+117
-53
lines changed
Open diff view settings
Filter options
Expand file treeCollapse file tree

1 file changed

+117
-53
lines changed
Open diff view settings
Collapse file

‎doc/api/console.markdown‎

Copy file name to clipboardExpand all lines: doc/api/console.markdown
+117-53Lines changed: 117 additions & 53 deletions
  • Display the source diff
  • Display the rich diff
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,37 +124,54 @@ 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
Used to calculate the duration of a specific operation. To start a timer, call
114-
the `console.time()` method, giving it a name as only parameter. To stop the
166+
the `console.time()` method, giving it a unique `label` as the only parameter. To stop the
115167
timer, and to get the elapsed time in milliseconds, just call the
116168
[`console.timeEnd()`][] method, again passing the
117-
timer's name as the parameter.
169+
timer's unique `label` as the parameter.
118170

119171
### console.timeEnd(label)
120172

121173
Stops a timer that was previously started by calling [`console.time()`][] and
122-
prints the result to the console:
174+
prints the result to stdout:
123175

124176
console.time('100-elements');
125177
for (var i = 0; i < 100; i++) {
@@ -130,18 +182,30 @@ prints the result to the console:
130182

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

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

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

138-
Same as [`console.error()`][].
204+
The `console.warn()` function is an alias for [`console.error()`][].
139205

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

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.