1,实现在终端同一行输出不同内容
import readline form 'readline'; console.clear(); setInterval(() => { //删除光标所在行 readline.clearLine(process.stdout, 0); //移动光标到行首 readline.cursorTo(process.stdout, 0, 0) process.stdout.write(new Date().toLocaleString(), 'utf-8'); }, 1000);
2, 实现进度条
import readline form 'readline'; console.clear(); let completed = 0; let total = 100; let length = 25; //进度条长度 var timer = setInterval(() => { readline.clearLine(process.stdout, 0); //删除光标所在行 readline.cursorTo(process.stdout, 0, 0); //移动光标到行首 let percent = (completed / total).toFixed(4); var cell_num = Math.floor(percent * length); // 计算需要多少个 █ 符号来拼凑图案 // 拼接黑色条 var cell = ''; for (var i = 0; i < cell_num; i++) { cell += '█'; } // 拼接灰色条 var empty = ''; for (var i = 0; i < length - cell_num; i++) { empty += '░'; } // 拼接最终文本 var cmdText = '进度: ' + (100 * percent).toFixed(2) + '% ' + cell + empty + ' ' + completed + '/' + total; process.stdout.write(cmdText, 'utf-8'); if(completed>=total){ clearInterval(timer); readline.cursorTo(process.stdout, 0, 2); console.log("完成"); } completed = completed + 2; }, 10);
如无特殊需要,可以参考完善的 npm 包:https://www.npmjs.com/package/progress
声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。