You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js实现单行多色控制台日志输出问题求助

让Node.js彩色日志在同一行输出的解决方案

没问题,我帮你调整代码!你现在的问题是每次调用console.log都会输出新的一行,只要把所有带颜色的日志片段合并到一次console.log调用里,就能实现同一行显示且保留各部分颜色啦。

修改后的代码:

const consoleColorWhite = '\x1b[37m%s\x1b[0m';
const consoleColorGreen = '\x1b[32m%s\x1b[0m';
const consoleColorRed = '\x1b[31m%s\x1b[0m';
const consoleColorYellow = '\x1b[33m%s\x1b[0m';
const consoleColorCyan = '\x1b[36m%s\x1b[0m';

exports.log = function(type, msg){
    let msgType = '';
    let msgTypeColor = consoleColorWhite;

    switch (type) {
        case 'inf':
            msgType = '[INF]';
            msgTypeColor = consoleColorGreen;
            break;
        case 'err':
            msgType = '[ERR]';
            msgTypeColor = consoleColorRed;
            break;
        case 'wrn':
            msgType = '[WRN]';
            msgTypeColor = consoleColorYellow;
            break;
        default:
            // 无有效类型时不输出类型标记
            msgType = '';
    }

    const dateTime = new Date();
    const dateTimeString = `[${dateTime.toLocaleDateString()} ${dateTime.toLocaleTimeString()}]`;

    // 核心:一次console.log输出所有片段,每个颜色模板对应一个内容参数
    console.log(
        `${msgType ? `${msgTypeColor} ` : ''}${consoleColorCyan} ${consoleColorWhite}`,
        msgType,
        dateTimeString,
        msg
    );
};

关键说明:

  1. 合并console.log调用:console.log支持接收多个参数,每个%s占位符会对应后面的一个参数,ANSI颜色控制码只会作用于对应的%s内容,不会互相干扰。
  2. 优化类型处理:直接在switch分支里生成带方括号的类型标记,减少额外的字符串拼接;无有效类型时自动跳过类型输出,避免空括号的尴尬。
  3. 简化字符串拼接:用ES6模板字符串重构时间戳生成逻辑,代码更简洁易读。

你可以测试一下,现在调用log('inf', '操作成功')就会在同一行显示绿色的[INF]、青色的时间戳和白色的消息啦!

内容的提问来源于stack exchange,提问作者peterHasemann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:19:38