• 【Node】node的Console模块使用。


    简言

    node:console 模块提供了一个简单的调试控制台,类似于网络浏览器提供的 JavaScript 控制台机制。

    Console

    node:console 模块提供了一个简单的调试控制台,类似于网络浏览器提供的 JavaScript 控制台机制。
    该模块输出两个特定组件:

    • 一个控制台类,包含 console.log()、console.error() 和 console.warn()等方法,可用于写入任何 Node.js 数据流。
    • 全局控制台实例,配置为写入 process.stdout 和 process.stderr。全局控制台无需调用 require(‘node:console’) 即可使用。

    全局控制台对象的方法既不像其类似的浏览器 API 那样始终是同步的,也不像所有其他 Node.js 流那样始终是异步的。更多信息,请参阅有关进程 I/O 的说明。

    使用全局控制台(console)的示例:

    console.log('hello world');
    // Prints: hello world, to stdout
    console.log('hello %s', 'world');
    // Prints: hello world, to stdout
    console.error(new Error('Whoops, something bad happened'));
    // Prints error message and stack trace to stderr:
    //   Error: 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 ${name}! Danger!`);
    // Prints: Danger Will Robinson! Danger!, to stderr 
    

    使用控制台类的示例:

    import { Console } from "node:console";
    import { createWriteStream } from "node:fs";
    import { join } from "node:path";
    import { URL, fileURLToPath } from "node:url";
    const __dirname = fileURLToPath(new URL("../../", import.meta.url));
    const ouput = createWriteStream(join(__dirname, "src/console/stdout.log"));
    
    const errOutput = createWriteStream(join(__dirname, "src/console/stderr.log"));
    
    const logger = new Console({ stdout: ouput, stderr: errOutput });
    
    const count = 5;
    logger.log("count : %d", count);
    
    logger.log("hello world");
    // Prints: hello world, to out
    logger.log("hello %s", "world");
    // Prints: hello world, to out
    logger.error(new Error("Whoops, something bad happened"));
    // Prints: [Error: Whoops, something bad happened], to err
    
    const name = "Will Robinson";
    logger.warn(`Danger ${name}! Danger!`);
    // Prints: Danger Will Robinson! Danger!, to err
    

    Class: Console 控制台类

    Console 类可用于创建具有可配置输出流的简单日志记录器,并可使用 require(‘node:console’).Console 或 console.Console(或它们的重组对应类)访问:

    const { Console } = require('node:console'); 
    // or
    const { Console } = console; 
    

    new Console(stdout[, stderr][, ignoreErrors]) 创建一个新的 Console实例

    new Console(options)

    参数:

    • options 配置对象
      • stdout —— 日志信息输出流
      • stderr —— 用于警告或错误输出
      • ignoreErrors —— 写入底层流时忽略错误。默认值:true。
      • colorMode —— 设置此控制台实例的颜色支持。设置为 true 可在检查数值时着色。设为 false 则在检查数值时禁用着色。设置为 "auto "后,颜色支持取决于 isTTY 属性的值和相应流上 getColorDepth() 返回的值。如果同时设置了 inspectOptions.colors,则无法使用此选项。默认值:“auto”。
      • inspectOptions —— 指定传递给 util.inspect() 的选项。
      • groupIndentation —— 设置组缩进。默认值:2。

    创建一个新的 Console,其中包含一个或两个可写流实例。stdout 是一个可写流,用于打印日志或信息输出。stderr 用于警告或错误输出。如果没有提供 stderr,则使用 stdout 代替 stderr。

    import { Console } from "node:console";
    import { createWriteStream } from "node:fs";
    import { join } from "node:path";
    import { URL, fileURLToPath } from "node:url";
    const __dirname = fileURLToPath(new URL("../../", import.meta.url));
    const ouput = createWriteStream(join(__dirname, "src/console/stdout.log"));
    
    const errOutput = createWriteStream(join(__dirname, "src/console/stderr.log"));
    
    const logger = new Console({ stdout: ouput, stderr: errOutput });
    
    const count = 5;
    logger.log("count : %d", count);
    
    logger.log("hello world");
    // Prints: hello world, to out
    logger.log("hello %s", "world");
    // Prints: hello world, to out
    logger.error(new Error("Whoops, something bad happened"));
    // Prints: [Error: Whoops, something bad happened], to err
    
    const name = "Will Robinson";
    logger.warn(`Danger ${name}! Danger!`);
    // Prints: Danger Will Robinson! Danger!, to err
    

    全局控制台是一个特殊的控制台,其输出会发送到 process.stdout 和 process.stderr。它相当于调用:

    const global = new Console({ stdout: process.stdout, stderr: process.stderr });
    global.log("12323");
    

    console.assert(value[, …message]) 打印断言信息

    console.assert() 会在值有误或省略时写入一条信息。它只会写入一条信息,不会影响执行。输出总是以 "断言失败 "开头。如果提供了信息,则使用 util.format() 格式化信息。

    如果值是真实的,则什么也不会发生。

    console.assert(true, 'does nothing');
    
    console.assert(false, 'Whoops %s work', 'didn\'t');
    // Assertion failed: Whoops didn't work
    
    console.assert();
    // Assertion failed 
    

    console.clear() 清空TTY

    当 stdout 是 TTY 时,调用 console.clear() 将尝试清除 TTY。当 stdout 不是 TTY 时,该方法不起任何作用。

    TTY —— TTY是由虚拟控制台,串口以及伪终端设备组成的终端设备。

    console.clear() 的具体操作可能因操作系统和终端类型而异。对于大多数 Linux 操作系统,console.clear() 的操作类似于 clear shell 命令。在 Windows 操作系统中,console.clear() 只清除 Node.js 二进制当前终端视口中的输出。

    console.count([label]) 计数

    参数:

    • label —— 计数器的显示标签。默认值:“default”。

    维护一个特定于标签的内部计数器,并将调用给定标签的 console.count() 次数输出到 stdout。

    > console.count()
    default: 1
    undefined
    > console.count('default')
    default: 2
    undefined
    > console.count('abc')
    abc: 1
    undefined
    > console.count('xyz')
    xyz: 1
    undefined
    > console.count('abc')
    abc: 2
    undefined
    > console.count()
    default: 3
    undefined
    > 
    

    console.countReset([label]) 计数重置

    重置标签专用的内部计数器。

    console.count("abc");
    console.countReset("abc");
    console.count("abc");
    
    

    console.debug(data[, …args]) 调试打印

    console.debug() 函数是 console.log() 的别名。
    在调试模式下这个语句相当于在此处打了一下断点。

    console.dir(obj[, options]) dir打印

    参数:

    • obj :
    • oprions : 配置对象
      • showHidden —— 如果为 “true”,则也将显示对象的非可数和符号属性。默认值:false。
      • depth —— 告诉 util.inspect() 在格式化对象时要递归多少次。这对于检查大型复杂对象非常有用。要让它无限制地递归,请传递 null。默认值:2。
      • colors —— 如果为 “true”,则输出将采用 ANSI 颜色代码样式。颜色可自定义;请参阅自定义 util.inspect() 颜色。默认值:false。

    在 obj 上使用 util.inspect(),并将结果字符串打印到 stdout。此函数会绕过在 obj 上定义的任何自定义 inspect() 函数。

    console.dirxml(…data) dirxml打印

    该方法调用 console.log(),并将收到的参数传递给它。该方法不会生成任何 XML 格式。

    console.dir(`[1,
      
                   2,
                              3]`);
    console.log(`[1,
      
                  2,
                             3]`);
    console.dirxml(`[1,
      
                  2,
                             3]`);
    

    console.error([data][, …args]) 错误信息打印

    以换行方式打印到 stderr。可以传递多个参数,第一个参数作为主要信息,所有其他参数作为替代值,类似于 printf(3)(参数全部传递给 util.format())。

    const code = 5;
    console.error('error #%d', code);
    // Prints: error #5, to stderr
    console.error('error', code);
    // Prints: error 5, to stderr 
    

    console.group([…label]) 增加缩进

    根据 groupIndentation 长度,增加后续行的缩进空格。
    如果提供了一个或多个标签,则先打印这些标签,而不增加缩进。

    console.groupCollapsed()

    console.group() 的别名。

    console.groupEnd() 减少缩进

    根据 groupIndentation 长度,以空格减少后续行的缩进。

    console.log(1);
    console.group();
    console.log(2);
    console.groupEnd();
    console.log(3);
    

    console.info([data][, …args]) 信息打印

    console.info() 函数是 console.log() 的别名。

    console.log([data][, …args]) 信息打印

    以换行方式打印到 stdout。可以传递多个参数,第一个参数作为主要信息,所有其他参数作为替代值,类似于 printf(3)(参数全部传递给 util.format())。

    const count = 5;
    console.log('count: %d', count);
    // Prints: count: 5, to stdout
    console.log('count:', count);
    // Prints: count: 5, to stdout 
    

    更多信息请参见 util.format()。

    console.table(tabularData[, properties]) 表格格式打印信息

    参数:

    • tabularData —— 数据
    • properties —— 用于构建表格的其他属性。
      尝试用 tabularData 的属性列(或使用属性)和 tabularData 的行构建一个表格并记录。如果无法解析为 tabular,则退回到只记录参数。
    // These can't be parsed as tabular data
    console.table(Symbol());
    // Symbol()
    
    console.table(undefined);
    // undefined
    
    console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);
    // ┌─────────┬─────┬─────┐
    // │ (index) │ a   │ b   │
    // ├─────────┼─────┼─────┤
    // │ 0       │ 1   │ 'Y' │
    // │ 1       │ 'Z' │ 2   │
    // └─────────┴─────┴─────┘
    
    console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);
    // ┌─────────┬─────┐
    // │ (index) │ a   │
    // ├─────────┼─────┤
    // │ 0       │ 1   │
    // │ 1       │ 'Z' │
    // └─────────┴─────┘ 
    
    console.table(
      [
        { a: 1, b: "Y" },
        { a: "Z", b: 2 },
      ],
      ["a", "b", "c"]
    );
    

    console.time([label]) 开始计时

    启动计时器,用于计算操作的持续时间。定时器由一个唯一的标签标识(label)。调用 console.timeEnd() 停止计时器并以合适的时间单位向 stdout 输出经过的时间时,请使用相同的标签。例如,如果经过时间为 3869ms,则 console.timeEnd() 会显示 “3.869s”。

    console.timeEnd([label]) 打印计时持续时间,并结束计时

    停止之前通过调用 console.time() 启动的计时器,并将结果打印到 stdout:

    console.time('bunch-of-stuff');
    // Do a bunch of stuff.
    console.timeEnd('bunch-of-stuff');
    // Prints: bunch-of-stuff: 225.438ms 
    

    console.timeLog([label][, …data]) 当前持续时间,打印data数据

    对于之前通过调用 console.time() 启动的计时器,会将经过的时间和其他数据参数打印到 stdout:

    console.time('process');
    const value = expensiveProcess1(); // Returns 42
    console.timeLog('process', value);
    // Prints "process: 365.227ms 42".
    doExpensiveProcess2(value);
    console.timeEnd('process'); 
    

    console.trace([message][, …args])

    向 stderr 打印字符串 “Trace:”,然后是 util.format() 格式化的信息和代码中当前位置的堆栈跟踪。

    console.trace('Show me');
    // Prints: (stack trace will vary based on where trace is called)
    //  Trace: Show me
    //    at repl:2:9
    //    at REPLServer.defaultEval (repl.js:248:27)
    //    at bound (domain.js:287:14)
    //    at REPLServer.runBound [as eval] (domain.js:300:12)
    //    at REPLServer. (repl.js:412:12)
    //    at emitOne (events.js:82:20)
    //    at REPLServer.emit (events.js:169:7)
    //    at REPLServer.Interface._onLine (readline.js:210:10)
    //    at REPLServer.Interface._line (readline.js:549:8)
    

    console.warn([data][, …args]) 警告信息打印

    console.warn() 函数是 console.error() 的别名。

    Inspector only methods --inspect 调试模式专用方法

    V8 引擎在通用 API 中公开了以下方法,但除非与检查器(–inspect 标志)一起使用,否则不会显示任何内容。

    console.profile([label])

    除非在检查器中使用,否则该方法不会显示任何内容。console.profile() 方法会启动一个带有可选标签的 JavaScript CPU 配置文件,直到调用 console.profileEnd()。然后,该配置文件将添加到检查器的配置文件面板中。

    console.profile('MyLabel');
    // Some code
    console.profileEnd('MyLabel');
    // Adds the profile 'MyLabel' to the Profiles panel of the inspector. 
    

    console.profileEnd([label])

    除非在检查器中使用,否则该方法不会显示任何内容。如果当前 JavaScript CPU 剖析会话已启动,则停止该会话,并将报告打印到检查器的 Profiles 面板。有关示例,请参阅 console.profile()。
    如果调用此方法时没有标签,则会停止最近启动的配置文件。

    console.timeStamp([label])

    除非在检查器中使用,否则该方法不会显示任何内容。console.timeStamp() 方法会在检查器的时间线面板中添加一个标有 "label "的事件。

    结语

    结束了。

  • 相关阅读:
    基于JavaWeb+SpringBoot+Vue超市管理系统的设计和实现
    【Java】枚举 Enum
    电子商务交易系统的设计与实现(javaee+mysql)
    使用Grunt shell方式交互处理数据
    【算法刷题 | 动态规划14】6.28(最大子数组和、判断子序列、不同的子序列)
    eNSP笔记①
    JVM笔记: JVM内存模型
    查找算法【平衡二叉树】 - 平衡二叉树的删除
    python毕业设计作品基于django框架 电影院购票选座系统毕设成品(5)任务书
    MySQL - UNION 与 UNION ALL
  • 原文地址:https://blog.csdn.net/qq_43231248/article/details/139408819