Libon

清空控制台打印内容

2022/09/03 通过 node 内置 readline 模块来读取、清空控制台打印 #JavaScript#nodejs#console

ToC

import process from 'node:process'
import readline from 'node:readline'

function clearScreen() {
  const repeatCount = process.stdout.rows - 2
  const blank = repeatCount > 0 ? '\n'.repeat(repeatCount) : ''
  console.log(blank)
  readline.cursorTo(process.stdout, 0, 0)
  readline.clearScreenDown(process.stdout)
}

可以用一下代码进行测试:

import process from 'node:process'
import readline from 'node:readline'

function clearScreen() {
  const repeatCount = process.stdout.rows - 2
  const blank = repeatCount > 0 ? '\n'.repeat(repeatCount) : ''
  console.log(blank)
  readline.cursorTo(process.stdout, 0, 0)
  readline.clearScreenDown(process.stdout)
}

function print() {
  for (let i = 0; i < 10; i++) {
    console.log(i)
  }

  setTimeout(clearScreen, 1000)
  setTimeout(print, 3000)
}

print()
CD ..
回顾上一篇
Level Logger