首页 > 解决方案 > 标准输出中的NodeJS child_process ansi

问题描述

我想得到类似的东西

[06:32:35] [Server thread/INFO]: [0;36;1m  |    [0;36;22m|__)   [0;32;22mLuckPerms [0;36;1mv4.3.73[m
[06:32:35] [Server thread/INFO]: [0;36;1m  |___ [0;36;22m|      [0;30;1mRunning on Bukkit - CraftBukkit[m

但我明白了

[06:05:02] [Server thread/INFO]:   |    |__)   LuckPerms v4.3.73
[06:05:02] [Server thread/INFO]:   |___ |      Running on Bukkit - CraftBukkit

使用 child_process 运行 minecraft 服务器时

prcs.stdout.on("data", function(d) {
    console.log(d.toString());
});

标签: javascriptnode.jsminecraftchild-process

解决方案


在不确切知道如何d形成的情况下,这里有一些符合您的示例的东西,可能不完全符合您的需要,但您可以随时尝试升级它(至少它不需要任何依赖项):

const versionRegExp = /v[0-9]+(\.[0-9]+)*$/;
d.toString().split("\n").forEach((line) => {
  // no idea what the spaces are made of
  const exploded = line.trim().split(/[ \t]+/);
  // add paddings to the first two structures
  const first = exploded.shift().padEnd(5, ' ');
  const second = exploded.shift().padEnd(7, ' ');
  // work out the content
  // condition based on `second`, or should it be remainder.match(versionRegExp) ?
  const remainder = 0 === second.indexOf('|__)')
    ? `[0;30;1m${exploded.join(' ').replace(versionRegExp, '[0;36;1m$&')}[m`
    : `[0;32;22m${exploded.join(' ')}[m`
  ;
  // format line and display
  console.log(`[0;36;1m${first}[0;36;22m${second}${remainder}`);
});

推荐阅读