Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear terminal window in Node.js readline shell

I have a simple readline shell written in Coffeescript:

rl = require 'readline'
cli = rl.createInterface process.stdin, process.stdout, null
cli.setPrompt "hello> "

cli.on 'line', (line) ->
  console.log line
  cli.prompt()

cli.prompt()

Running this displays a prompt:

$ coffee cli.coffee 
hello> 

I would like to be able to hit Ctrl-L to clear the screen. Is this possible?

I have also noticed that I cannot hit Ctrl-L in either the node or coffee REPLs either.

I am running on Ubuntu 11.04.

like image 680
mkopala Avatar asked Jan 11 '12 01:01

mkopala


People also ask

How do you clear a node in terminal?

clear() operates like the clear shell command in terminal. On Windows, console. clear() will clear the current terminal viewport for the Node.

How do you clear the terminal in react JS?

CTRL + L as Shortcut to clear Developer Console.


2 Answers

You can watch for the keypress yourself and clear the screen.

process.stdin.on 'keypress', (s, key) ->
  if key.ctrl && key.name == 'l'
    process.stdout.write '\u001B[2J\u001B[0;0f'

Clearing is done with ASCII control sequences like those written here: http://ascii-table.com/ansi-escape-sequences-vt-100.php

The first code \u001B[2J instructs the terminal to clear itself, and the second one \u001B[0;0f forces the cursor back to position 0,0.

Note

The keypress event is no longer part of the standard Node API in Node >= 0.10.x but you can use the keypress module instead.

like image 60
loganfsmyth Avatar answered Sep 23 '22 02:09

loganfsmyth


In the MAC terminal, to clear the console in NodeJS, you just hit COMMAND+K just like in Google Developer Tools Console so I'm guessing that on Windows it would be CTRL+K.

like image 23
Adrian Oprea Avatar answered Sep 26 '22 02:09

Adrian Oprea