Консоль¶
АПИ является удовлетворительным. Совместимость с NPM имеет высший приоритет и не будет нарушена кроме случаев явной необходимости.
Модуль node:console предоставляет простую отладочную консоль, которая похожа на механизм консоли JavaScript, предоставляемый веб-браузерами.
Модуль экспортирует два специфических компонента:
- Класс Console с методами console.log() , console.error() и console.warn() , которые могут быть использованы для записи в любой поток Node.js.
- Глобальный экземпляр console настроен на запись в process.stdout и process.stderr . Глобальная console может использоваться без вызова require(‘node:console’) .
Предупреждение: Методы объекта глобальной консоли не являются ни последовательно синхронными, как API браузера, на которые они похожи, ни последовательно асинхронными, как все остальные потоки Node.js. Дополнительную информацию смотрите в заметке о процессах ввода-вывода.
Пример с использованием глобальной console :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
console.log('hello world'); // Печатает: hello world, в stdout console.log('hello %s', 'world'); // Выводит: hello world, на stdout console.error(new Error('Упс, случилось что-то плохое')); // Выводит сообщение об ошибке и трассировку стека в stderr: // Ошибка: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Опасность $имя>! Опасность!`); // Выводит: Danger Will Robinson! Danger!, to stderr
Пример с использованием класса Console :
1 2 3 4 5 6 7 8 9 10 11 12 13 14
const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Печатает: hello world, в out myConsole.log('hello %s', 'world'); // Печатает: hello world, to out myConsole.error(new Error('Упс, случилось что-то плохое')); // Печатает: [Error: Whoops, something bad happened], to err const name = 'Уилл Робинсон'; myConsole.warn(`Danger $name>! Danger!`); // Prints: Danger Will Robinson! Опасность!, to err
Класс: Console ¶
Класс Console может быть использован для создания простого регистратора с настраиваемыми потоками вывода, доступ к которому можно получить с помощью require(‘node:console’).Console или console.Console (или их деструктурированных аналогов):
const Console > = require('node:console');
Console
The node:console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A Console class with methods such as console.log() , console.error() , and console.warn() that can be used to write to any Node.js stream.
- A global console instance configured to write to process.stdout and process.stderr . The global console can be used without calling require(‘node:console’) .
Warning: The global console object’s methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.
Example using the global console :
Example using the Console class:
The Console class can be used to create a simple logger with configurable output streams and can be accessed using either require(‘node:console’).Console or console.Console (or their destructured counterparts):
M new Console(stdout[, stderr][, ignoreErrors])
- options Object
- stdout stream.Writable
- stderr stream.Writable
- ignoreErrors boolean Ignore errors when writing to the underlying streams. Default: true .
- colorMode boolean | string Set color support for this Console instance. Setting to true enables coloring while inspecting values. Setting to false disables coloring while inspecting values. Setting to ‘auto’ makes color support depend on the value of the isTTY property and the value returned by getColorDepth() on the respective stream. This option can not be used, if inspectOptions.colors is set as well. Default: ‘auto’ .
- inspectOptions Object Specifies options that are passed along to util.inspect() .
- groupIndentation number Set group indentation. Default: 2 .
Creates a new Console with one or two writable stream instances. stdout is a writable stream to print log or info output. stderr is used for warning or error output. If stderr is not provided, stdout is used for stderr .
The global console is a special Console whose output is sent to process.stdout and process.stderr . It is equivalent to calling:
M console.assert(value[, . message])
- value any The value tested for being truthy.
- . message any All arguments besides value are used as error message.
console.assert() writes a message if value is falsy or omitted. It only writes a message and does not otherwise affect execution. The output always starts with «Assertion failed» . If provided, message is formatted using util.format() .
If value is truthy, nothing happens.
When stdout is a TTY, calling console.clear() will attempt to clear the TTY. When stdout is not a TTY, this method does nothing.
The specific operation of console.clear() can vary across operating systems and terminal types. For most Linux operating systems, console.clear() operates similarly to the clear shell command. On Windows, console.clear() will clear only the output in the current terminal viewport for the Node.js binary.
Maintains an internal counter specific to label and outputs to stdout the number of times console.count() has been called with the given label .
Resets the internal counter specific to label .
The console.debug() function is an alias for console.log() .
- obj any
- options Object
- showHidden boolean If true then the object’s non-enumerable and symbol properties will be shown too. Default: false .
- depth number Tells util.inspect() how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. To make it recurse indefinitely, pass null . Default: 2 .
- colors boolean If true , then the output will be styled with ANSI color codes. Colors are customizable; see customizing util.inspect() colors. Default: false .
Uses util.inspect() on obj and prints the resulting string to stdout . This function bypasses any custom inspect() function defined on obj .
This method calls console.log() passing it the arguments received. This method does not produce any XML formatting.
Prints to stderr with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format() ).
If formatting elements (e.g. %d ) are not found in the first string then util.inspect() is called on each argument and the resulting string values are concatenated. See util.format() for more information.
Increases indentation of subsequent lines by spaces for groupIndentation length.
If one or more label s are provided, those are printed first without the additional indentation.
Decreases indentation of subsequent lines by spaces for groupIndentation length.
The console.info() function is an alias for console.log() .
Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format() ).
See util.format() for more information.
M console.table(tabularData[, properties])
Try to construct a table with the columns of the properties of tabularData (or use properties ) and rows of tabularData and log it. Falls back to just logging the argument if it can’t be parsed as tabular.
Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique label . Use the same label when calling console.timeEnd() to stop the timer and output the elapsed time in suitable time units to stdout . For example, if the elapsed time is 3869ms, console.timeEnd() displays «3.869s».
Stops a timer that was previously started by calling console.time() and prints the result to stdout :
M console.timeLog([label][, . data])
For a timer that was previously started by calling console.time() , prints the elapsed time and other data arguments to stdout :
M console.trace([message][, . args])
Prints to stderr the string ‘Trace: ‘ , followed by the util.format() formatted message and stack trace to the current position in the code.
The console.warn() function is an alias for console.error() .
The following methods are exposed by the V8 engine in the general API but do not display anything unless used in conjunction with the inspector ( —inspect flag).
This method does not display anything unless used in the inspector. The console.profile() method starts a JavaScript CPU profile with an optional label until console.profileEnd() is called. The profile is then added to the Profile panel of the inspector.
This method does not display anything unless used in the inspector. Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. See console.profile() for an example.
If this method is called without a label, the most recently started profile is stopped.
This method does not display anything unless used in the inspector. The console.timeStamp() method adds an event with the label ‘label’ to the Timeline panel of the inspector.
Output to the command line using Node.js
Node.js provides a console module which provides tons of very useful ways to interact with the command line.
It is basically the same as the console object you find in the browser.
The most basic and most used method is console.log() , which prints the string you pass to it to the console.
If you pass an object, it will render it as a string.
You can pass multiple variables to console.log , for example:
and Node.js will print both.
We can also format pretty phrases by passing variables and a format specifier.
- %s format a variable as a string
- %d format a variable as a number
- %i format a variable as its integer part only
- %o format a variable as an object
console.clear() clears the console (the behavior might depend on the console used)
console.count() is a handy method.
What happens is that console.count() will count the number of times a string is printed, and print the count next to it:
You can just count apples and oranges:
The console.countReset() method resets counter used with console.count().
We will use the apples and orange example to demonstrate this.
Notice how the call to console.countReset(‘orange’) resets the value counter to zero.
There might be cases where it’s useful to print the call stack trace of a function, maybe to answer the question how did you reach that part of the code?
You can do so using console.trace() :
This will print the stack trace. This is what’s printed if we try this in the Node.js REPL:
You can easily calculate how much time a function takes to run, using time() and timeEnd()
As we saw console.log is great for printing messages in the Console. This is what’s called the standard output, or stdout .
console.error prints to the stderr stream.
It will not appear in the console, but it will appear in the error log.
You can color the output of your text in the console by using escape sequences. An escape sequence is a set of characters that identifies a color.
You can try that in the Node.js REPL, and it will print hi! in yellow.
However, this is the low-level way to do this. The simplest way to go about coloring the console output is by using a library. Chalk is such a library, and in addition to coloring it also helps with other styling facilities, like making text bold, italic or underlined.
You install it with npm install chalk@4 , then you can use it:
Using chalk.yellow is much more convenient than trying to remember the escape codes, and the code is much more readable.
Check the project link posted above for more usage examples.
Progress is an awesome package to create a progress bar in the console. Install it using npm install progress
This snippet creates a 10-step progress bar, and every 100ms one step is completed. When the bar completes we clear the interval: