Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Get Cursor Position in Terminal with Node.js
module.exports = function(callback) {
require('child_process').exec('./', function(error, stdout, stderr) {
callback(error, JSON.parse(stdout));
# based on a script from
exec < /dev/tty
oldstty=$(stty -g)
stty raw -echo min 0
# on my system, the following line can be replaced by the line below it
echo -en "\033[6n" > /dev/tty
# tput u7 > /dev/tty # when TERM=xterm (and relatives)
IFS=';' read -r -d R -a pos
stty $oldstty
# change from one-based to zero based so they work with: tput cup $row $col
row=$((${pos[0]:2} - 1)) # strip off the esc-[
col=$((${pos[1]} - 1))
echo \{\"row\":$row,\"column\":$col\}
var getCursorPosition = require('./cursor-position');
getCursorPosition(function(error, position) {
console.log('row:', position.row, 'column:', position.column)

This comment has been minimized.

Copy link
Owner Author

@lancejpollard lancejpollard commented Sep 22, 2012

You can also possibly calculate the cursor position by:

  • reading each line in the terminal window
  • adding a new line
  • re-reading each line and comparing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment