在nodejs中应用进度条库和记录器库

Applying progress bar library with logger library in nodejs

我想将 'cli-progress' 与 'pino logger' 整合来创建这样的东西 其中进度条位置一致

[=======================] 100%
log1
log2
log3
...

但我得到的是这个,酒吧会被日志塞满

[===                    ] 10%
log1
log2
[==========             ] 30%
log3
...
[=======================] 100%

我想知道我是否可以实现这样的东西,我可以将两个写入流分离到终端

比如

[ writes for bar to be consistently on top ]
[ writes for logs will take the rest of the space]

据我所知,我不可能替换“pino”,有没有办法解决这个问题?

如果您使用 Node >= 17,您甚至可以使用“vanilla”JS(在“no-package”的意义上)。

Readline interface 可能正是您所需要的。

请注意,Promises API(允许移动光标)仍处于试验阶段,我不会将其用于生产工具

一个即时制作的小例子:

import * as readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'node:process';

const testScript = () => {
  // creates a normal interface
  const rl = readline.createInterface({ input, output });
  // creates a Promise-based interface with the same stdout
  const rlProm = new readline.Readline(output);
  // writing to stdout
  // PLEASE NOTE THAT YOU NEED TO USE \n, OTHERWISE THE STREAM IS NOT FLUSHED
  rl.write('this is a simple test\n');
  // moves the cursor 3 lines below the current position
  rlProm.moveCursor(0, 3);
  // commit "commits" the changes made to rlProm
  rlProm.commit();
  // writing to stdout
  rl.write('still a test\n');
  // moving to the third line of stdout
  rlProm.cursorTo(0, 3);
  // clearing the line
  rlProm.clearLine(0);
  // commiting changes to stdout
  rlProm.commit();
  // now that the line has been cleared, we can re-write on it
  rl.write('this line has been replaced\n');
  // moving again to the end of the script, meaning you have to keep track of what you're doing
  rlProm.cursorTo(0, 8);
  rlProm.commit();

  // finally, closing stdout stream
  rl.close();
};

testScript();

您可以利用 clearLine 功能不断地重写您的加载栏,给人一种同时写入两个流的错觉。

现在你肯定可以用更少的代码用一个包来实现它,但是因为我从来没有在 JS 中做过,只在 C 中用 curses 库,我不知道任何。


要具体回答关于 pino 包的问题,​​我认为你不能,因为我没有在他们的 API docs.[=16 中看到任何移动光标的方法=]