1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

console出力の同じ行を更新する

Last updated at Posted at 2021-01-31

tl;dr

readlineライブラリのcusorTo()を使うと、consoleの同じ行を更新することができます。

説明

パッケージインストール時などにconsoleの同じ行が更新されて経過が表示されることがありますが、Node.jsで実現できます。

普通のconsole.logの場合

let time = 0;

setInterval(() => {
  console.log(`time: ${++time}`);
}, 1000);

実行結果

time: 1
time: 2
time: 3
time: 4
...( 以下、略 )...

readlineを使った場合

readlineはNode.jsに標準でバンドルされています。

import readline from 'readline'

let time = 0

setInterval(() => {
  readline.cursorTo(process.stdout, 0);
  process.stdout.write(`time: ${++time}`);
}, 1000)

実行結果(5秒後)

time: 5

以上。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?