Introduction to the

In this article, we’ll learn how to use most of the methods in the Node.jsConsole class more effectively.

The premise condition

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

useconsole.log.console.info, andconsole.debug

The console.log method is printed to standard output, either on the terminal or the browser console. It outputs a string by default, but can be used in conjunction with a template string to modify what it returns.

console.log(string, substitution)
Copy the code

The console.info and console.debug methods operate the same as console.log.

You can use console.debug by default in the Firefox browser console, but to use it in Chrome, you must set the logging level to Verbose in the All Levels menu.

The parameters in the template string are passed to util.format, which processes these parameters, replacing each substitution token with the corresponding conversion value.

The supported replacement tokens are.

%s

const msg = `Using the console class`;
console.log('%s', msg);
console.log(msg);
Copy the code

This code outputs the following.

OutputUsing the console class
Using the console class
Copy the code

%s is the default replacement mode.

%d.%f.%i%o

const circle = (radius = 1) = > {
  const profile = {};
  const pi = 22/7;
  profile.diameter = 2 * pi * radius;
  profile.circumference = pi * radius * 2;
  profile.area = pi * radius * 2;
  profile.volume = 4/3 * 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: %o', profile);
  console.log('Diameter %d, Area: %f, Circumference %i', profile.diameter, profile.area, profile.circumference)
}

circle();
Copy the code

This code outputs the following.

OutputThis circle has a radius of: 1 cm This circle has a circumference of: 6.285714285714286 cm This circle has an area of: 6 cm^2 The profile of This cirlce is: {diameter: Circumference: 6.285714285714286, circumference: 6.285714285714286, area: 6.285714285714286, volume: 7} Diameter 6, area: 6.285714285714286, Circumference (6)Copy the code
  • %dWill be replaced by a number (integer or floating point).
  • %fWill be replaced by a floating value.
  • %iWill be replaced by an integer.
  • %oWill be replaced by an object.

%o is particularly handy because we don’t need json.stringify to expand our object, since it displays all of the object’s properties by default.

Note that you can use as many token substitutions as you want. They are simply replaced in the order of the arguments you passed.

%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');
Copy the code

This code outputs the following.

After the %c tag is replaced, the text we pass to console.log is affected by the style, but the previous text remains unchanged without the style.

useconsole.table

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

console.table(tabularData, [properties])
Copy the code

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

An array of

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);
Copy the code

For a simple array of depth 1, the first column in the table has a header index. Under the index heading in the first column is the index of the array, and the items in the array are listed under the value heading in 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);
Copy the code

object

For objects of depth 1, the key of the object is listed under the index heading, and the value of the object is listed under the second column heading.

const inventory = { apples: 200.mangoes: 50.avocados: 300.kiwis: 50 };
console.table(inventory);
Copy the code

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);
Copy the code

There are also nested objects.

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

Here, we specify that we only want to see data pushed down the column.

console.table(workoutLog, 'push');
Copy the code

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

It’s convenient, isn’t it?

Try passing an object with some values as an array to console.table!

useconsole.dir

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

Returns an object formatted by Node’s util.expect function.

Nested or child objects in the input object can be expanded under the disclosure triangle.

console.dir(object, options);
// where options = { showHidden: true ... }
Copy the code

Let’s take a look at this.

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

This is the Console for Chrome.

useconsole.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);
Copy the code

With console.dir, the rendered tree can be expanded by clicking on the disclosure triangle, where the child nodes can be seen.

Its output is similar to what we found under the Elements TAB of the browser.

This is what happens when we pass in some HTML from a Wikipedia page.

const toc = document.querySelector('#toc');
console.dirxml(toc);
Copy the code

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

console.dirxml(document)
Copy the code

That’s what happens when we pass in an object.

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

useconsole.assert

The first argument passed to the function is a value to test for truth. All other parameters passed are considered information and are printed if the passed value is not evaluated as true.

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

console.assert(value, [...messages])
Copy the code

Here is a basic example.

console.assert(false.'Assertion failed');
Copy the code
OutputAssertion failed: Assertion failed
Copy the code

Now, let’s have some fun. We’ll build a small testing framework using console.Assert

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(1.1), 2)); // Test passed 2 === 2
console.log(test('sum', sum(), 0));    // Test passed 0 === 0
console.log(test('sum', sum, 2));      // Assertion failed for sum
console.log(test('sum', sum(3.3), 4)); // Assertion failed for sum
Copy the code

Run the above in your Node REPL or browser console and see what happens.

useconsole.errorconsole.warn

These are basically the same thing. They all print whatever string is passed to them.

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

console.warn(string, substitution);
Copy the code

Console. error, on the other hand, prints a danger symbol before the message is passed.

console.error(string, substitution);
Copy the code

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

Here is a mini-logging function that uses console.error.

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(1.1), 3);
Copy the code

useconsole.trace(label)

The console method prints the string Trace:, followed by the label passed to the function, and then the 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'));
Copy the code

useconsole.count(label)

Count starts and increments 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();
Copy the code
getOccurences('foolish');
Copy the code

Here, we see the word foolish recorded twice. Note the word every time it appears in a phrase.

[secondary_label]
foolish: 1
foolish: 2
2
Copy the code

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

useconsole.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();
Copy the code
getOccurences('foolish');
Copy the code
[secondary_label]
foolish: 1
foolish: 1
2
Copy the code

We can see that our getOccurences function returns 2, because Foolish does appear twice in this sentence, but since our counter is reset on each match, it records Foolish: 1 twice.

useconsole.time(label)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 provides label as an argument to the function.

console.time('<timer-label>');
console.timeEnd('<timer-label>');
Copy the code

We can calculate how long 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();
Copy the code

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

OutputVivaldi Beethoven Ludovico timerLabel: 0.69091796875 MSCopy the code

The looping function completed the looping operation over the array in 0.6909ms.

conclusion

Finally, we’ve come to the end of this tutorial.

Note that this tutorial does not cover non-standard uses of console classes such as console.profile, console.profileEnd, and console.timeLog.