Create console in javascript

Window Console Object

The console object provides access to the browser’s debugging console.

The console object is a property of the window object.

The console object is accessed with:

window.console or just console

Examples

Console Object Methods

Method Description
assert() Writes an error message to the console if a assertion is false
clear() Clears the console
count() Logs the number of times that this particular call to count() has been called
error() Outputs an error message to the console
group() Creates a new inline group in the console. This indents following console messages by an additional level, until console.groupEnd() is called
groupCollapsed() Creates a new inline group in the console. However, the new group is created collapsed. The user will need to use the disclosure button to expand it
groupEnd() Exits the current inline group in the console
info() Outputs an informational message to the console
log() Outputs a message to the console
table() Displays tabular data as a table
time() Starts a timer (can track how long an operation takes)
timeEnd() Stops a timer that was previously started by console.time()
trace() Outputs a stack trace to the console
warn() Outputs a warning message to the console

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

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.

      Источник

      Консоль JavaScript в вашем браузере

      В процессе программирования на JavaScript появляется необходимость выводить значения переменных. К примеру, это можно делать функцией alert( ). Но если использовать её несколько раз, тогда придётся закрывать всплывающее окно, чтобы увидеть следующее. Это неудобно, поэтому на помощь приходит консоль, встроенная в браузер.

      Как открыть JavaScript консоль в браузере?

      Если вы пользуетесь одним из популярных браузеров (Chrome, FireFox, Safari, Opera), то в них уже встроена консоль JavaScript, в которую можно выводить отладочную информацию во время разработки. Для этого откройте страницу сайта, на которой находится JS код для тотладки, и кликните на клавишу F12 на клавиатуре. Откроется панель разработчика.

      В большинстве браузеров средства разработки называются более-менее одинаково и имеют очень схожий функционал. Далее в статье будет рассматриваться браузер FireFox.

      Теперь необходимо переключить вкладку вверху открывшегося окна на «Консоль». Кликните на эту вкладку с помощью курсора мыши: Разберёмся с иконоками и опциями, которые есть в этой закладке:

      • Иконка корзины — очищает лог (лог — это список событий, строчки текстовых записи)
      • Непрерывные логи — если поставить эту галочку, то при перезагрузки страницы лог не будет очищаться автоматически.
      • «Ошибки», «Предупреждения», «Лог» . — эти закладки отключают вывод сообщений. К примеру, кликните по пункту «Ошибки» и снимите выделение, тогда в консоль не будут записываться предупреждение об ошибках.

      Как вывести переменную JavaScript в консоль?

      Попробуем написать на странице JavaScript код и перезагрузить её, чтобы он выполнился. В коде используем функцию console.log( ), которая выводит значение содержимого в скобках. То есть если поставить в скобки переменную, то в консоли будет показано её значение:

      Заглянем в консоль и увидим значение объекта: Чтобы увидеть подробную информацию, кликните на иконку стрелочки слева на интересующей строчке: Таким способом можно выводить не только массивы и объекты, но и простые переменные. К сожалению, если выводить сразу несколько значений, то не будет понятно что к чему относится. Продемонстрируем это:

      var a = 'Мышь'; var b = 'Сыр'; var c = 100; console.log(a); console.log(b); console.log(c);

      Результат выполнения этого кода будет таким: Такой вывод не слишком информативен. К счастью, внутри скобок функции console.log( ) можно использовать объединение строк. Поэтому предлагаем записать дополнительную отладочную информацию в выводимые строки:

      var a = 'Мышь'; var b = 'Сыр'; var c = 100; console.log('Значение переменной "a" = ' + a); console.log('Значение переменной "b" = ' + b); console.log('Значение переменной "c" = ' + c);

      Теперь вывод в консоль будет более информативным. И можно использовать функцию console.log( ) десятки раз, не боясь запутаться в значениях, которые попадают в консоль:

      Рекомендуем ознакомиться со статьёй «Операции со строками в JavaScript», если возникли вопросы к объединению строк.

      К сожалению, это можно делать только с простыми переменными (строки/числа) и массивами (в том числе многомерными), но с объектами так сделать не получится, потому что будет выведено «[object Object]» вместо значения:

      Источник

      Читайте также:  Css sci fi 3 hardwired 3
Оцените статью