Heim  >  Artikel  >  Web-Frontend  >  Eine kurze Diskussion zur Verwendung der Konsole in Node.js

Eine kurze Diskussion zur Verwendung der Konsole in Node.js

青灯夜游
青灯夜游nach vorne
2021-10-29 10:12:272143Durchsuche

Wie verwende ich die Konsole in Node.js? In diesem Artikel erfahren Sie, wie Sie die Konsole in Node.js verwenden, und lernen die meisten Methoden in der Konsolenklasse kennen. Ich hoffe, dass er Ihnen weiterhilft!

Eine kurze Diskussion zur Verwendung der Konsole in Node.js

In diesem Artikel erfahren Sie, wie Sie die meisten Methoden in der Node.js-Klasse console effizienter nutzen können. [Empfohlenes Lernen: „nodejs Tutorialconsole 类中的大多数方法。【推荐学习:《nodejs 教程》】

前提条件

本教程在Chrome浏览器70.0.3538.77版本和Node.js 8.11.3版本中得到验证。

使用console.log,console.info, 和console.debug

console.log 方法会打印到标准输出,无论是终端还是浏览器控制台。
它默认输出字符串,但可以与模板字符串结合使用,以修改其返回的内容。

console.log(string, substitution)

console.infoconsole.debug 方法在操作上与 console.log 相同。

你可以在Firefox浏览器控制台中默认使用console.debug ,但要在Chrome浏览器中使用它,你必须在所有级别菜单中把日志级别设置为Verbose

Eine kurze Diskussion zur Verwendung der Konsole in Node.js

模板字符串中的参数被传递给 util.format它将处理这些参数,用相应的转换值替换每个替换标记。

支持的替换代币是。

%s

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

这段代码将输出以下内容。

OutputUsing the console class
Using the console class

%s 是默认的替换模式。

%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();

这段代码将输出以下内容。

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: 6.285714285714286, circumference: 6.285714285714286, area: 6.285714285714286, volume: 7}
Diameter 6, Area: 6.285714285714286, Circumference 6
  • %d 将被一个数字(整数或浮点数)所替代。
  • %f 将被一个浮动值所取代。
  • %i 将被一个整数取代。
  • %o 将被一个对象所取代。

%o 特别方便,因为我们不需要用 JSON.stringify来展开我们的对象,因为它默认显示对象的所有属性。

请注意,你可以使用任意多的令牌替换。它们只是按照你传递的参数的顺序被替换。

%c

这个替换令牌将CSS样式应用于被替换的文本。

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');

这段代码将输出以下内容。

Eine kurze Diskussion zur Verwendung der Konsole in Node.js

%c 替换标记之后,我们传递给console.log 的文本会受到样式的影响,但之前的文本则保持原样,没有样式。

使用console.table"]

Voraussetzungen

Dieses Tutorial wurde in der Chrome-Browserversion 70.0.3538.77 und Node.js-Version 8.11.3 überprüft.

Verwenden Sie console.log, console.info und console.debug Die Methode

console.log druckt auf der Standardausgabe, unabhängig davon, ob es sich um ein Terminal oder eine Browserkonsole handelt.
Es gibt standardmäßig eine Zeichenfolge aus, kann jedoch in Verbindung mit einer Vorlagenzeichenfolge verwendet werden, um die Rückgabe zu ändern.

console.table(tabularData, [properties])

Die Methoden console.info und console.debug sind betriebsmäßig identisch mit console.log.

Eine kurze Diskussion zur Verwendung der Konsole in Node.jsSie können Firefox

console.debug wird standardmäßig in verwendet Browserkonsole, aber in Um es in Chrome

zu verwenden, müssen Sie die Protokollebene im Menü

Alle Ebenen

auf

Verbose🎜 einstellen. 🎜🎜Eine kurze Diskussion zur Verwendung der Konsole in Node.js🎜🎜Vorlage Parameter in der Zeichenfolge werden an
util.format🎜Diese Parameter werden mit dem entsprechenden behandelt Der Konvertierungswert ersetzt jeden Ersatztoken. 🎜🎜Unterstützte Ersatztoken sind. 🎜

🎜%s🎜🎜
const books = ['The Silmarillion', 'The Hobbit', 'Unfinished Tales'];
console.table(books);
🎜Dieser Code gibt den folgenden Inhalt aus. 🎜
const authorsAndBooks = [['Tolkien', 'Lord of The Rings'],['Rutger', 'Utopia For Realists'], ['Sinek', 'Leaders Eat Last'], ['Eyal', 'Habit']];
console.table(authorsAndBooks);
🎜%s ist der Standard-Ersetzungsmodus. 🎜

🎜%d, %f, %i, %o🎜🎜<pre class="brush:js;toolbar:false;">const inventory = { apples: 200, mangoes: 50, avocados: 300, kiwis: 50 }; console.table(inventory);</pre>🎜Dieser Code gibt den folgenden Inhalt aus. 🎜<pre class="brush:js;toolbar:false;">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);</pre><ul> <li> <code>%d wird durch eine Zahl (Integer oder Float) ersetzt.
  • %f wird durch einen Float-Wert ersetzt.
  • %i wird durch eine Ganzzahl ersetzt.
  • %o wird durch ein Objekt ersetzt.
  • 🎜%o ist besonders praktisch, da wir
    JSON.stringify🎜 um unser Objekt zu erweitern, da alle Eigenschaften des Objekts angezeigt werden standardmäßig. 🎜🎜Bitte beachten Sie, dass Sie so viele Token-Ersetzungen verwenden können, wie Sie möchten. Sie werden einfach in der Reihenfolge ersetzt, in der Sie die Argumente übergeben. 🎜

    🎜%c🎜🎜🎜Dieses Ersetzungstoken wendet CSS-Stile auf den zu ersetzenden Text an. 🎜
    const workoutLog = { Monday: { push: &#39;Incline Bench Press&#39;, pull: &#39;Deadlift&#39;}, Wednesday: { push: &#39;Weighted Dips&#39;, pull: &#39;Barbell Rows&#39;}};
    console.table(workoutLog);
    🎜Dieser Code gibt Folgendes aus. 🎜🎜Eine kurze Diskussion zur Verwendung der Konsole in Node.js🎜🎜at Nach dem %c-Ersetzungs-Tag wird der Text, den wir an console.log übergeben, vom Stil beeinflusst, der vorherige Text bleibt jedoch ohne Stil unverändert. 🎜

    🎜Verwenden Sie console.table🎜🎜🎜Der erste übergebene Parameter sind die Daten, die in Form einer Tabelle zurückgegeben werden sollen. Das zweite ist ein Array ausgewählter Spalten, die angezeigt werden sollen. 🎜
    console.table(workoutLog, &#39;push&#39;);
    🎜Diese Methode formatiert die an sie übergebenen Eingaben in einer Tabelle und protokolliert dann das Eingabeobjekt nach der Tabellendarstellung. 🎜🎜🎜Arrays🎜🎜🎜Wenn ihm ein Array als Daten übergeben wird, ist jedes Element im Array eine Zeile in der Tabelle. 🎜
    console.dir(object, options);
    // where options = { showHidden: true ... }
    🎜🎜🎜🎜Für ein einfaches Array mit Tiefe 1 hat die erste Spalte in der Tabelle den Kopfindex. Unter der Überschrift „Index“ in der ersten Spalte befindet sich der Index des Arrays, und die Elemente im Array werden unter der Überschrift „Wert“ in der zweiten Spalte aufgelistet. 🎜🎜Das passiert bei verschachtelten Arrays. 🎜
    const authorsAndBooks = [[&#39;Tolkien&#39;, &#39;Lord of The Rings&#39;],[&#39;Rutger&#39;, &#39;Utopia For Realists&#39;], [&#39;Sinek&#39;, &#39;Leaders Eat Last&#39;], [&#39;Eyal&#39;, &#39;Habit&#39;]];
    console.table(authorsAndBooks);

    Eine kurze Diskussion zur Verwendung der Konsole in Node.js

    对象

    对于深度为1的对象,对象的键会列在索引标题下,而对象中的值则列在第二列标题下。

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

    Eine kurze Diskussion zur Verwendung der Konsole in Node.js

    对于嵌套的对象。

    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);

    Eine kurze Diskussion zur Verwendung der Konsole in Node.js

    还有一些嵌套的对象。

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

    Eine kurze Diskussion zur Verwendung der Konsole in Node.js

    这里,我们指定只想看到列推下的数据。

    console.table(workoutLog, &#39;push&#39;);

    Eine kurze Diskussion zur Verwendung der Konsole in Node.js

    要对某一列下的数据_进行排序_,只需点击该列标题。

    很方便,是吗?

    试着把一个带有一些数值的对象作为数组传给console.table!

    使用console.dir

    传给这个函数的第一个参数是要记录的对象,而第二个参数是一个包含选项的对象,这些选项将定义结果输出的格式,或者对象中的哪些属性将被显示。

    返回的是一个由node的util.expect函数格式化的对象。

    输入对象中的嵌套或子对象可在披露三角形下展开。

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

    让我们看看这个动作。

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

    这里是Chrome浏览器的控制台。

    Eine kurze Diskussion zur Verwendung der Konsole in Node.js

    使用console.dirxml

    这个函数将为传递给它的XML/HTML渲染一棵交互式树。如果无法渲染节点树,它默认为一个Javascript对象。

    console.dirxml(object|nodeList);

    console.dir ,渲染的树可以通过点击披露三角形来扩展,在其中可以看到子节点。

    它的输出类似于我们在浏览器的Elements标签下发现的输出。

    这是我们从维基百科页面传入一些HTML时的情况。

    const toc = document.querySelector(&#39;#toc&#39;);
    console.dirxml(toc);

    Eine kurze Diskussion zur Verwendung der Konsole in Node.js

    让我们从这个网站上的一个页面传入一些HTML。

    console.dirxml(document)

    1Eine kurze Diskussion zur Verwendung der Konsole in Node.js

    这就是我们传入一个对象时的情况。

    1Eine kurze Diskussion zur Verwendung der Konsole in Node.js

    试着在一些HTML上调用console.dir ,看看会发生什么。

    使用console.assert

    传递给函数的第一个参数是一个要测试是否为真值的值。所有传递的其他参数被认为是信息,如果传递的值没有被评估为真值,就会被打印出来。

    Node REPL将抛出一个错误,停止后续代码的执行。

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

    下面是一个基本的例子。

    console.assert(false, &#39;Assertion failed&#39;);
    OutputAssertion failed: Assertion failed

    现在,让我们找点乐子。我们将建立一个小型测试框架,使用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(&#39;sum&#39;, sum(1,1), 2)); // Test passed 2 === 2
    console.log(test(&#39;sum&#39;, sum(), 0));    // Test passed 0 === 0
    console.log(test(&#39;sum&#39;, sum, 2));      // Assertion failed for sum
    console.log(test(&#39;sum&#39;, sum(3,3), 4)); // Assertion failed for sum

    使用console.errorconsole.warn

    这两个基本上是相同的。它们都会打印传递给它们的任何字符串。

    然而,console.warn 在信息传递之前会打印出一个三角形的警告符号。

    console.warn(string, substitution);

    1Eine kurze Diskussion zur Verwendung der Konsole in Node.js

    console.error ,在信息传递前打印出一个危险符号。

    console.error(string, substitution);

    1Eine kurze Diskussion zur Verwendung der Konsole in Node.js

    让我们注意到,字符串替换可以用与console.log 方法相同的方式来应用。

    下面是一个使用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);

    1Eine kurze Diskussion zur Verwendung der Konsole in Node.js

    使用console.trace(label)

    这个控制台方法将打印字符串Trace: ,后面是传递给函数的标签,然后是堆栈跟踪到函数的当前位置。

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

    1Eine kurze Diskussion zur Verwendung der Konsole in Node.js

    使用console.count(label)

    Count将开始并递增一个名为label 的计数器。

    让我们建立一个单词计数器来看看它是如何工作的。

    const getOccurences = (word = &#39;foolish&#39;) => {
      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, &#39;&#39;).split(&#39; &#39;);
      wordsFromPhraseArray.forEach((element, idx) => {
        if (element === word) {
          count ++;
          console.count(word);
        }
      });
      return count;
    }
    
    getOccurences();
    getOccurences(&#39;foolish&#39;);

    在这里,我们看到foolish 这个词被记录了两次。该词在短语中每出现一次就记录一次。

    [secondary_label]
    foolish: 1
    foolish: 2
    2

    我们可以用这个方法来查看一个函数被调用了多少次,或者我们的代码中的某一行被执行了多少次。

    使用console.countReset(label)

    顾名思义,这将重置一个计数器,该计数器有一个由console.count 方法设置的label

    const getOccurences = (word = &#39;foolish&#39;) => {
      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, &#39;&#39;).split(&#39; &#39;);
      wordsFromPhraseArray.forEach((element, idx) => {
        if (element === word) {
          count ++;
          console.count(word);
          console.countReset(word);
        }
      });
      return count;
    }
    
    getOccurences();
    getOccurences(&#39;foolish&#39;);
    [secondary_label]
    foolish: 1
    foolish: 1
    2

    我们可以看到,我们的getOccurences 函数返回2,因为在这句话中确实有两次出现foolish ,但由于我们的计数器在每次匹配时都被重置,所以它记录了两次foolish: 1

    使用console.time(label)console.timeEnd(label)

    console.time 函数启动一个定时器,并将label 作为参数提供给该函数,而console.timeEnd 函数停止一个定时器,并将label 作为参数提供给该函数。

    console.time(&#39;<timer-label>&#39;);
    console.timeEnd(&#39;<timer-label>&#39;);

    我们可以通过向两个函数传递相同的label 名称来计算出运行一个操作所需的时间。

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

    我们可以看到计时器停止后显示的计时器标签与时间值相对应。

    OutputVivaldi
    Beethoven
    Ludovico
    timerLabel: 0.69091796875ms

    循环函数花了0.6909ms完成了对数组的循环操作。

    结论

    最后,我们已经来到了本教程的结尾。

    请注意,本教程没有涵盖console 类的非标准使用,如console.profileconsole.profileEnd ,和console.timeLog

    更多编程相关知识,请访问:编程入门!!

    Das obige ist der detaillierte Inhalt vonEine kurze Diskussion zur Verwendung der Konsole in Node.js. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

    Stellungnahme:
    Dieser Artikel ist reproduziert unter:juejin.cn. Bei Verstößen wenden Sie sich bitte an admin@php.cn löschen