Skip to content

修改 Node.js 控制台输出结果 #172

@Dream4ever

Description

@Dream4ever

需求描述

在做 05_IIS 日志统计分析 的时候,为了改善用户体验,需要像 Vue-Cli 那样,在屏幕上实时显示当前这本书的图书配套资源,处理到第几个 IIS 日志文件了。

重点是每本书的处理进度只在一行上显示,这就需要在处理到下一个日志文件的时候,清空上一个日志文件的处理结果,并输出最新结果。

实现过程

最开始尝试用 ansi-escapes 这个库,结果发现不好用。

后来 Google js remove terminal output line,在 Is there a way to erase the last line of output? 中,给出了原生方法:

process.stdout.moveCursor(0, -1) // up one line
process.stdout.clearLine(1) // from cursor to end

这个方法用到了 Node.js 原生的 TTY 模块,该模块包含 WriteStream 这个类,而当 process.stdout.fd 指向文件时,process.stdout 的返回值也是一个 WriteStream 类,从而可以调用 TTY 模块的 moveCursor 方法和 clearLine 方法,来修改控制台的输出结果。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions