Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8833

Node.jsのCLIでローディングを実装する

$
0
0

はじめに

とある情報をエクスポートするプログラムを作成していた時に、情報量が多くエクスポートに時間が少しかかるとプログラムが動作しているのかどうか不安になるときがありました。
そんなとき、よく見る、ローディング表示をすれば動作しているのかハングしてしまっているのかがわかるので、実装したいと思いました。

環境

  • Node v10.16.3
  • Typescript 4.0.2
  • npm 6.14.9
  • git version 2.23.0.windows.1
  • Windows 10 Pro

参考サイト

【Node.js】CLIでロード中にクルクル回るアレ(スピナー)を作る

コード

  • Loading.tsローディングスタート及びエンドの関数を提供
Loading.ts
importrlfrom'readline'constspin_char=["","","","","","","","","",""]letspin_count=0;constspin=(message:string)=>{process.stdout.write('\x1B[?25l')//カーソルを消すrl.clearLine(process.stdout,0)//行をすべて削除rl.moveCursor(process.stdout,-9999,0)//一番左側に戻るprocess.stdout.write(`${spin_char[spin_count]}${message}`)//spin_charの配列で描画spin_count++//要素番号計算spin_count>=spin_char.length?spin_count=0:null//要素番号のリセット}exportconstloading=(msg:string)=>setInterval(()=>{spin(msg);},200);exportconstendloading=(loading:NodeJS.Timeout,msg:string)=>{clearInterval(loading)rl.clearLine(process.stdout,0)// 行をすべて削除process.stdout.write(`\n${msg}`)//end Messageprocess.stderr.write('\x1B[?25h')//ローディングで消したカーソルを戻す}

使用例

loading('ローディング中に表示したい文字列')
endLoading(loadingの返り値 ,'終了時に表示したい文字列')
上記をそれぞれローディングスタート、ローディングエンドのタイミングで呼ぶ

QueryCollection.ts
//start Loadingconstloadingstart=loading('Query a collection')//Discovery queryconstresquery=awaitqueryCollection(url,apikey,environmentid,collectionid,version)//end Loadingendloading(loadingstart,'Query a collection Finished!!')

使用イメージ

cliLoading (1).gif

最後に

Loading.tsのspin_charや表示速度等をカスタマイズしていけば自分好みのローディングアニメーションを作ることもできますので是非活用ください。


Viewing all articles
Browse latest Browse all 8833

Trending Articles