gpt4 book ai didi

node.js - 如何在 Node js 中以干净可读的格式显示输出?

转载 作者:太空宇宙 更新时间:2023-11-03 23:48:58 24 4
gpt4 key购买 nike

我是 Node.js 新手。我编写了一个脚本,可以生成 5 个子进程并从中捕获日志,截至目前,日志看起来一团糟。

Screen shot of current output

但我想以更清晰的格式显示输出,就像每行都被重用并且数据被记录在进程 ID 旁边。像这样的东西: enter image description here

下面是我的代码:

var state = "node stealth.js ";
var exec = require('child_process').exec;


workers = 5



p_list = [];

for (var i = 0; i < workers; i++) {
(function(i){
var child = exec(state+'user'+i);
console.log('started Worker '+i)
// Add the child process to the list for tracking
p_list.push({process:child, content:""});

// Listen for any response:
child.stdout.on('data', function (data) {

console.log(child.pid, data);
p_list[i].content += data;
process.stdout.cursorTo(i);
process.stdout.clearLine();
process.stdout.write(child.pid+data);
process.stdout.write("\n"); // end the line

});

// Listen for any errors:
child.stderr.on('data', function (data) {
console.log(child.pid, data);
p_list[i].content += data;
});

// Listen if the process closed
child.on('close', function(exit_code) {
console.log('Closed before stop: Closing code: ', exit_code);
});
})(i)
}

最佳答案

您正在寻找VT100 Terminal Control Escape Sequences 。这些序列允许移动光标或 color the text .

示例

console.log('Line 1');
console.log('Line 2');
console.log('\x1B[1AAgain line 2');

开头的 \x1B[1A 序列将光标向上移动一行,因此后面的文本会覆盖前面的文本。结果如下所示:

Line 1
Again line 2

有关更多序列,请查看页面中有关 cursor movement 的部分.

关于node.js - 如何在 Node js 中以干净可读的格式显示输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60054140/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com