Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use console in Node.js

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "how to use console in Node.js". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

In this article, we will learn how to use most of the methods in the Node.js console class more effectively. [recommended: "nodejs tutorial"]

prerequisite

This tutorial is validated in Chrome browser version 70.0.3538.77 and Node.js version 8.11.3.

Use console.log,console.info, and console.debug

The console.log method prints to standard output, whether it's the terminal or the browser console.

It outputs strings by default, but can be used in conjunction with template strings to modify what it returns.

Console.log (string, substitution)

The console.info and console.debug methods are operationally the same as console.log.

You can use console.debug by default in the Firefox browser console, but to use it in Chrome browsers, you must set the log level to Verbose in all level menus.

The parameters in the template string are passed to util.format, which processes them, replacing each replacement tag with the corresponding conversion value.

The supported replacement tokens are.

% sconst msg = `class`; console.log ('% Using the console, msg); console.log (msg)

This code will output the following.

OutputUsing the console classUsing the console class

S is the default replacement mode.

% dpi% freco% oconst circle = (radius = 1) = > {const profile = {}; const pi = 22max 7; profile.diameter = 2 * pi * radius; profile.circumference = pi * radius * 2; profile.area = pi * radius * 2; profile.volume = 4and3 * pi * radius ^ 3; console.log ('This circle has a radius of:% d cm', radius); console.log (' This circle has a circumference of:% f cm', profile.diameter) Console.log ('This circle has an area of:% I cm ^ 2', profile.area); console.log ('The profile of this cirlce is:% oasis, profile); console.log (' Diameter% d, Area:% f, Circumference% iBy, profile.diameter, profile.area, profile.circumference)} circle ()

This code will output the following.

OutputThis circle has a radius of: 1 cmThis circle has a circumference of: 6.285714285714286 cmThis circle has an area of: 6cm ^ 2the profile of this cirlce is: {diameter: 6.285714285714286, circumference: 6.285714285714286, area: 6.285714285714286, volume: 7} Diameter 6, Area: 6.285714285714286, Circumference 6

% f will be replaced by a floating value.

% I will be replaced by an integer.

% o will be replaced by an object.

% o is particularly convenient because we don't need to expand our object with JSON.stringify because it displays all the properties of the object by default.

% c

This replacement token applies the CSS style to the replaced text.

Console.log ('LOG LEVEL:% c OK',' color: green; font-weight: normal'); console.log ('LOG LEVEL:% c PRIORITY',' color: blue; font-weight: medium'); console.log ('LOG LEVEL:% c WARN',' color: red; font-weight: bold'); console.log ('ERROR HERE')

This code will output the following.

After% c replaces the tag, the text we pass to console.log is affected by the style, but the previous text remains intact and has no style.

Use console.table

The first parameter passed to it is the data to be returned as a table. The second is an array of selected columns to display.

Console.table (tabularData, [properties])

This method formats the input passed to it as a table, and then records the input object after the table is represented.

Array

If an array is passed to it as data, each element in the array will be a row in the table.

Const books = ['The Silmarillion',' The Hobbit', 'Unfinished Tales']; console.table (books)

For a simple array of depth 1, the first column in the table has a header index. Under the index heading of the first column is the index of the array, and the items in the array are listed under the value heading of the second column.

This is the case with nested arrays.

Const authorsAndBooks = [['Tolkien',' Lord of The Rings'], ['Rutger',' Utopia For Realists'], ['Sinek',' Leaders Eat Last'], ['Eyal',' Habit']]; console.table (authorsAndBooks)

Object

For objects with a depth of 1, the keys of the object are listed under the index heading, and the values in the object are listed under the second column heading.

Const inventory = {apples: 200, mangoes: 50, avocados: 300, kiwis: 50}; console.table (inventory)

For nested objects.

Const forexConverter = {asia: {rupee: 1.39, renminbi: 14.59, ringgit: 24.26}, africa: {rand: 6.49, nakfa: 6.7, kwanza:0.33}, europe: {swissfranc: 101.60, gbp: 130, euro: 115.73}}; console.table (forexConverter)

There are also some nested objects.

Const workoutLog = {Monday: {push: 'Incline Bench Press', pull:' Deadlift'}, Wednesday: {push: 'Weighted Dips', pull:' Barbell Rows'}}; console.table (workoutLog)

Console.table (workoutLog, 'push')

To sort the data under a column, simply click on the column header.

It's convenient, isn't it?

Use console.dir

The first parameter passed to this function is the object to record, and the second parameter is an object that contains options that define the format of the result output or which properties in the object will be displayed.

Returns an object formatted by the util.expect function of node.

Nesting or sub-objects in the input object can be expanded under the disclosure triangle.

Console.dir (object, options); / / where options = {showHidden: true.}

Let's see this move.

Const user = {details: {firstName: 'Immanuel', lastName:' Kant'}, height: `1.83m "`, weight: '90kg, age:' 80kg, occupation: 'Philosopher', nationality:' German', books: [{name: 'Critique of Pure Reason', pub:' 1781mm,} {name: 'Critique of Judgement', pub:' 1790,}, {name: 'Critique of Practical Reason', pub:' 1788,}, {name: 'Perpetual Peace', pub:' 1795,},], death: '1804'}} console.dir (user)

This is the console of the Chrome browser.

Use console.dirxml

This function will render an interactive tree for the XML/HTML passed to it. If the node tree cannot be rendered, it defaults to a Javascript object.

Console.dirxml (object | nodeList)

Unlike console.dir, the rendered tree can be expanded by clicking on the disclosure triangle, where you can see the child nodes.

This is what happens when we import some HTML from Wikipedia pages.

Const toc = document.querySelector ('# toc'); console.dirxml (toc)

Let's pass in some HTML from a page on this site.

Console.dirxml (document)

This is what happens when we pass in an object.

Try calling console.dir on some HTML and see what happens.

Use console.assert

The first argument passed to the function is a value to test whether it is true. All other parameters passed are considered information, and if the passed value is not evaluated as true, it will be printed.

Node REPL will throw an error to stop the execution of subsequent code.

Console.assert (value, [... messages])

Here is a basic example.

Console.assert (false, 'Assertion failed'); OutputAssertion failed: Assertion failed

Now, let's have some fun.

Const sum = (a = 0, b = 0) = > Number (a) + Number (b); function test (functionName, actualFunctionResult, expected) {const actual = actualFunctionResult; const pass = actual = expected; console.assert (pass, `Assertion failed for ${functionName} `); return `Test passed ${actual} = ${expected}`;} console.log (test ('sum', sum (1CH1), 2)); / / Test passed 2 = = 2console.log (test (' sum', sum (), 0)) / / Test passed 0 = 0console.log (test ('sum', sum, 2)); / / Assertion failed for sumconsole.log (test (' sum', sum (3), 4)); / / Assertion failed for sum uses console.error and console.warn

The two are basically the same. They all print any strings passed to them.

However, console.warn prints out a triangular warning symbol before the message is transmitted.

Console.warn (string, substitution)

Console.error (string, substitution)

Let's note that string substitution can be applied in the same way as the console.log method.

Const sum = (a = 0, b = 0) = > Number (a) + Number (b); function otherTest (actualFunctionResult, expected) {if (actualFunctionResult! = = expected) {console.error (new Error (`Test failed ${actualFunctionResult}! = = ${expected} `));} else {/ / pass}} otherTest (sum (1m 1), 3)

Use console.trace (label)

This console method prints the string Trace:, followed by a label passed to the function, and then a stack trace to the current position of the function.

Function getCapital (country) {const capitalMap = {belarus: 'minsk', australia:' canberra', egypt: 'cairo', georgia:' tblisi', latvia: 'riga', samoa:' apia'}; console.trace ('Start trace here'); return Object.keys (capitalMap). Find (item = > item = = country)? CapitalMap [country]: undefined;} console.log (getCapital ('belarus')); console.log (getCapital (' accra'))

Use console.count (label)

Count will start and increment a counter called label.

Let's set up a word counter to see how it works.

Const getOccurences = (word = 'foolish') = > {const phrase = `Oh me! Oh life! Of the questions of these recurring, Of the endless trains of the faithless, of cities fill'd with the foolish, Of myself forever reproaching myself, for who more foolish than I, and who more faithless? `; let count = 0; const wordsFromPhraseArray = phrase.replace (/ [,.!?] / igm,'). Split ('); wordsFromPhraseArray.forEach ((element, idx) = > {if (element = word) {count + +; console.count (word);}}); return count } getOccurences (); getOccurences ('foolish')

Here, we see that the word foolish has been recorded twice. The word is recorded every time it appears in the phrase.

[secondary_label] foolish: 1foolish: 22

We can use this method to see how many times a function has been called, or how many times a line in our code has been executed.

Use console.countReset (label)

As the name implies, this resets a counter that has a label set by the console.count method.

Const getOccurences = (word = 'foolish') = > {const phrase = `Oh me! Oh life! Of the questions of these recurring, Of the endless trains of the faithless, of cities fill'd with the foolish, Of myself forever reproaching myself, for who more foolish than I, and who more faithless? `; let count = 0; const wordsFromPhraseArray = phrase.replace (/ [,.!?] / igm,'). Split ('); wordsFromPhraseArray.forEach ((element, idx) = > {if (element = = word) {count + +; console.count (word); console.countReset (word)) }}); return count;} getOccurences (); getOccurences ('foolish'); [secondary_label] foolish: 1foolish: 12

We can see that our getOccurences function returns 2 because foolish does appear twice in this sentence, but because our counter is reset each time it matches, it records foolish: 1 twice.

Use console.time (label) and console.timeEnd (label)

The console.time function starts a timer and provides label as an argument to the function, while the console.timeEnd function stops a timer and supplies label as an argument to the function.

Console.time ('); console.timeEnd (')

We can calculate the time it takes to run an operation by passing the same label name to both functions.

Const users = ['Vivaldi',' Beethoven', 'Ludovico']; const loop = (array) = > {array.forEach ((element, idx) = > {console.log (element);})} const timer = () = > {console.time (' timerLabel'); loop (users); console.timeEnd ('timerLabel');} timer ()

We can see that the timer label displayed after the timer stops corresponds to the time value.

OutputVivaldiBeethovenLudovicotimerLabel: 0.69091796875ms

The loop function takes 0.6909ms to complete the loop operation on the array.

This is the end of the introduction to "how to use console in Node.js". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report