简体   繁体   English

我如何在 NodeJS 中编写一个 CLI 应用程序来清除终端然后恢复它

[英]How do I write a CLI app in NodeJS which clears the terminal and then restores it afterwards

I want to write an interactive command line app which clears the contents of the terminal and then restores it upon exiting, the way that linux commands like vim and less do.我想编写一个交互式命令行应用程序,它清除终端的内容,然后在退出时恢复它,就像vimless那样的 linux 命令的方式。 How can I do this with Node.js?我如何使用 Node.js 执行此操作?

I can clear the terminal using console.clear() , but I'm not sure how to restore it to its original state when my app exits.我可以使用console.clear()清除终端,但我不确定如何在我的应用程序退出时将其恢复到原来的 state。

To answer my own question...回答我自己的问题...

Turns out you need to use the alternative buffer , used by other "full screen" terminal apps like less and vim .结果你需要使用替代 buffer ,由其他“全屏”终端应用程序使用,如lessvim You can do this using ANSI escape codes :您可以使用ANSI 转义码执行此操作:

/** Call this at the start of your program */
const enableAlternativeBuffer = () =>
  process.stdout.write("\u001B[?1049h");

/** Call this before exiting your program */
const disableAlternativeBuffer = () =>
  process.stdout.write("\u001B[?1049l");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM