跳到主要内容

命令行进度条实现 cli-progress

前言

我需要用 nodejs 去实现从服务端下载或者上传文件的情况,直接用命令行输出文本来显示进度条对于我而言实在是不美观,因此稍微搜索下了,发现命令行实现进度条还是非常简单的

原理

使用 cli-progress 这个库,可以非常方便的实现命令行进度条,

安装

npm install cli-progress
yarn add cli-progress

使用


## 基本使用

```javascript
const cliProgress = require('cli-progress');

// 创建一个进度条实例
const progressBar = new cliProgress.SingleBar({
format: '进度 |{bar}| {percentage}% || {value}/{total} 文件 || 文件index{fileKey}',
barCompleteChar: '\u2588',
barIncompleteChar: '\u2591',
hideCursor: true
});

let fileList = Array.from({ length: 144 }, (_, index) => index + 1);


const uploadFile = () => {
// 启动进度条加载
progressBar.start(fileList.length, 0);

// 模拟文件上传
Promise.all(
fileList.map((item, index) => {
return new Promise((resolve) => {
setTimeout(() => {
// update 方法可以更新进度条中显示的其他信息,显示更多自定义的内容
progressBar.update({ fileKey: item });
progressBar.increment(); // 每次完成文件上传后更新一次
resolve();
}, 1000);
});
})
).then(() => {
progressBar.stop(); // 完成进度条加载
});
}

uploadFile()

⚠️ 注意

如果进度条出现多行显示,并不是保持在一行显示,有可能是命令行窗口尺寸太小导致的,可以试着把命令行窗口放大看看